我想将圆300px向右移动然后停止它。我不知道我怎么能做到。当我在寻找一些教程时,我总是看到无穷无尽的循环。在文档中,我读到了时间间隔,但我不认为这个问题的好主意。我想让它看起来很漂亮,所以我想让它每1px移动并清除它。我想让它慢慢运行。
这是我的代码:
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
c.beginPath();
c.arc(100, 300, 100, 0, 2 * Math.PI, false);
c.stroke();
for (var i = 0; i < 300; i++) {
console.log("dasd");
c.beginPath();
// c.clearRect(0, 0, window.innerWidth, window.innerHeight);
c.arc(100 + i, 300, 100, 0, 2 * Math.PI, false);
c.stroke();
}
&#13;
canvas {
border: 1px solid black;
}
body {
margin: 0;
}
&#13;
<canvas></canvas>
&#13;
答案 0 :(得分:3)
您应该使用requestAnimationFrame
- 您可以阅读有关canvas animation
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
var start = null;
function step(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
c.beginPath();
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
c.arc(100 + progress, 100, 100, 0, 2 * Math.PI, false);
c.stroke();
if (progress < 300) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
canvas {
border: 1px solid black;
}
body {
margin: 0;
}
<canvas></canvas>