我正在尝试使用键盘光标键为Canvas上的圆设置动画。问题是clearRect()函数未正确使用,并且当您使用光标键时,有一条古怪的线条用圆圈绘制。
我尝试重新排序包括cleaRect()函数的代码,但这无济于事。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="keycode.js" defer></script>
<title>Example Javascript</title>
</head>
<body onload="setup()">
<canvas width="1000" height="1000" style="border: 1px solid black">
Your browser does not support canvas.
</canvas><br>
<input type="button" value="Move">
</body>
</html>
这是JavaScript代码
console.log("Script is connected");
let canvas = window.document.querySelector("Canvas");
let ctx = canvas.getContext("2d");
let increment = 0;
function setup() {
ctx.arc(canvas.width / 2, canvas.height / 2, 100, 0, 2 * Math.PI);
ctx.fillStyle = "lightblue";
ctx.fill();
ctx.stroke();
window.addEventListener("keydown", function (event) {
if (event.keyCode === 37) {
ctx.clearRect(0, 0, 1000, 1000);
increment += 200;
ctx.arc(canvas.width / 2 - increment, canvas.height / 2, 100, 0, 2 * Math.PI);
ctx.fillStyle = "lightblue";
ctx.fill();
ctx.stroke();
console.log(increment);
}
if (event.keyCode === 38) {
ctx.clearRect(0, 0, 10000, 1000);
increment += 200;
ctx.arc(canvas.width / 2, canvas.height / 2 - increment, 100, 0, 2 * Math.PI);
ctx.fillStyle = "lightblue";
ctx.fill();
ctx.stroke();
console.log(increment);
}
if (event.keyCode === 39) {
ctx.clearRect(0, 0, 10000, 1000);
increment += 200;
ctx.arc(canvas.width / 2 + increment, canvas.height / 2, 100, 0, 2 * Math.PI);
ctx.fillStyle = "lightblue";
ctx.fill();
ctx.stroke();
console.log(increment);
}
if (event.keyCode === 40) {
ctx.clearRect(0, 0, 1000, 1000);
increment += 200;
ctx.arc(canvas.width / 2, canvas.height / 2 + increment, 100, 0, 2 * Math.PI);
ctx.fillStyle = "lightblue";
ctx.fill();
ctx.stroke();
console.log(increment);
}
}, true);
}
答案 0 :(得分:0)
您使用clearRect()很好。问题是您的代码只有一个打开的路径,每次按下一个键都会对其进行扩展,因此,当您调用ctx.fill()和ctx.stroke()时,它会遵循越来越长的路径。
向每个案例添加beginPath()和closePath(),您将不再获得 多余的线条等。
赞:
ctx.beginPath();
ctx.arc(canvas.width / 2 - increment, canvas.height / 2, 100, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = "lightblue";
ctx.fill();
ctx.stroke();