Gerade jetzt draw()
ist immer Aufruf der Funktion draw()
. Zu stoppen, dass ein if
hinzufügen, bevor draw()
Aufruf:
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);
.d {
width: 93%;
height: auto;
z-index: 1;
position: absolute;
}
<canvas id="canvas" class="d" width="1838" height="1050"></canvas>
Vielleicht ein wenig klarer, aber weiter fortgeschritten ist, Lösung könnte sein setInterval()
zu verwenden, die eine Funktion läuft jeden n Sekunden (anstelle von setTimeout()
, die es läuft nur einmal nach n Sekunden:
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);
.d {
width: 93%;
height: auto;
z-index: 1;
position: absolute;
}
<canvas id="canvas" class="d" width="1838" height="1050"></canvas>
Wie Sie sehen können, ist dies etwas effizienter, da wir nicht jedes Mal die canvas
und ctx
erhalten müssen.
Es ist viel vorzuziehen zu sagen 'setTimeout (function() {zeichnen (x, y);} '. –
Wann und wie willst du es stoppen? –