【发布时间】:2019-03-30 02:14:36
【问题描述】:
我正在尝试使用键盘光标键为 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);
}
【问题讨论】:
标签: javascript html canvas automatic-ref-counting