我做了一个游戏,玩家按下矩形在随机位置移动会增加分数。这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<canvas id = "c" width = "500" height = "500"></canvas>
<canvas id = "d" width = "60" height = "60" onclick = "inc()"></canvas>
<style>
body {
margin:0;
padding:0;
background-color:blue;
}
#d {
position:absolute;
}
</style>
<script>
var can = document.getElementById("c");
var can2 = document.getElementById("d");
can.height = window.innerHeight;
can.width = window.innerWidth;
can2.height = window.innerHeight;
can2.width = window.innerWidth;
var s = can.getContext("2d");
var s2 = can2.getContext("2d");
var points = 0;
function move() {
h = Math.ceil(Math.random()*(can2.height-60))+20;
w = Math.ceil(Math.random()*(can2.width-50))+20;
s2.clearRect(0, 0, window.innerHeight, window.innerWidth);
s2.fillRect(this.w, this.h, 60, 60);
}
function inc() {
s.clearRect(0, 0, window.innerHeight, window.innerWidth);
s.fillText(points++, 300, 40);
return points;
}
s.font = "bold 35px Arial";
s.textAlign = points;
s.fillText(points, 300, 40);
s2.fillStyle = "#DEF012";
s2.fillRect(60, 60, 58, 55);
setInterval(move, 200);
</script>
</body>
</html>
但是当矩形移动时,旁边的矩形颜色会卡住。我怎样才能移动矩形而不出现这个问题?
最佳答案
参数在您对 clearRect 的调用中是倒退的。
另请注意,您似乎还想将 #c Canvas 设为 position:absolute。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<canvas id = "c" width = "500" height = "500"></canvas>
<canvas id = "d" width = "60" height = "60" onclick = "inc()"></canvas>
<style>
body {
margin:0;
padding:0;
background-color:blue;
}
#d {
position:absolute;
}
</style>
<script>
var can = document.getElementById("c");
var can2 = document.getElementById("d");
can.height = window.innerHeight;
can.width = window.innerWidth;
can2.height = window.innerHeight;
can2.width = window.innerWidth;
var s = can.getContext("2d");
var s2 = can2.getContext("2d");
var points = 0;
function move() {
h = Math.ceil(Math.random()*(can2.height-60))+20;
w = Math.ceil(Math.random()*(can2.width-50))+20;
s2.clearRect(0, 0, window.innerWidth, window.innerHeight);
//s2.clearRect(0, 0, window.innerHeight, window.innerWidth);
s2.fillRect(this.w, this.h, 60, 60);
}
function inc() {
s.clearRect(0, 0, window.innerHeight, window.innerWidth);
s.fillText(points++, 300, 40);
return points;
}
s.font = "bold 35px Arial";
s.textAlign = points;
s.fillText(points, 300, 40);
s2.fillStyle = "#DEF012";
s2.fillRect(60, 60, 58, 55);
setInterval(move, 200);
</script>
</body>
</html>
关于javascript - 为什么 Canvas 矩形的颜色卡住了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48509248/