function draw(x, y)
{
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = "rgba(0,110,150,1)";
ctx.fillRect (x, 370, 20, 20);
ctx.restore();
x += 41;
var loop = setTimeout('draw('+x+','+y+')',70);
}
draw(10, 20);
.d{
width: 93%;
height: auto;
z-index: 1;
position: absolute;
}
<canvas id="canvas" class="d" width="1838" height="1050"></canvas>
答案 0 :(得分:2)
loop
需要在函数范围之外。然后在其上调用clearTimeout
将停止循环。
var loop;
function draw(x,y) {
...
loop = setTimeout (...); // no "var"
...
}
...
draw (0,0);
setTimeout (function () {
clearTimeout (loop);
}, 5000); // will stop the loop after 5 seconds
答案 1 :(得分:0)
现在draw()
总是调用函数draw()
。要停止,请在致电if
之前添加draw()
:
function draw(x, y)
{
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = "rgba(0,110,150,1)";
ctx.fillRect (x, 370, 20, 20);
ctx.restore();
x += 41;
// Only add another dot if there are fewer than 20 dots
if (x < 800)
setTimeout(function() { draw(x, y) }, 70);
}
draw(10, 20);
&#13;
.d {
width: 93%;
height: auto;
z-index: 1;
position: absolute;
}
&#13;
<canvas id="canvas" class="d" width="1838" height="1050"></canvas>
&#13;
也许稍微更清晰但更高级的解决方案可能是使用setInterval()
,每隔 n 秒运行一个函数(而不是仅运行它的setTimeout()
< em>在 n 秒之后:
function draw(x, y) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var loop = setInterval(function() {
// setInterval() returns an indentifier for the timer; we can cancel
// the interval with clearInterval()
if (x > 800)
clearInterval(loop)
ctx.save();
ctx.fillStyle = "rgba(0,110,150,1)";
ctx.fillRect(x, 370, 20, 20);
ctx.restore();
x += 41;
}, 70)
}
draw(10, 20);
&#13;
.d {
width: 93%;
height: auto;
z-index: 1;
position: absolute;
}
&#13;
<canvas id="canvas" class="d" width="1838" height="1050"></canvas>
&#13;
正如您所看到的,这稍微提高效率,因为我们不需要每次都获得canvas
和ctx
。