開始をクリックすると、すでに開始されているループと並行して実行される新しいループが開始され、どちらが最初に実行されるかに応じて、キャンバスがクリアされて 2 回塗りつぶされます (または、ループを開始した回数だけ - ちらつきがより顕著になります)。になります)。
ループが何度も開始されないようにするメカニズムが必要です。1 つの方法は、フラグを使用することです。また、ループと描画を少し分離してコードをリファクタリングすることをお勧めします。
ライブデモはこちら
/// put these outside, no need to re-allocate them each time
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var x = 0;
var isRunning = false;
/// all loop-related here:
function loop() {
/// call draw from inside the loop instead
draw(x, 0); /// you are never using y so I just set 0 here...
x += 5;
if (isRunning && x <= w) {
requestAnimationFrame(loop); /// this is a better alternative
//setTimeout(loop, 100); /// optionally, but not recommended
} else {
isRunning = false; /// box is outside visible area so we'll stop..
}
}
/// keep draw() "clean", no loop code in here:
function draw(x, y) {
/// no need for save/restore here...
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "rgb(0, 200, 0)";
ctx.fillRect(x, 20, 50, 50);
}
fillStyle
入力が間違っていました。スペースを入れないでください(rgb(...
他の回答で述べたように - ただし、この場合は塗りつぶしスタイルが黒になるだけです)。さらにcanvas
、html にタグの閉じ括弧がありません。
ボタンのクリックを確認するには、HTML で JS をインライン化する代わりに、次の方法をお勧めします。
/// check for button clicks (start):
document.getElementById('start').addEventListener('click', function() {
if (!isRunning) { /// are we running? if not start loop
isRunning = true; /// set flag so we can prevent multiple clicks
x = 0; /// reset x
loop(); /// now we start the *loop*
}
}, false);
そしてあなたのhtmlで:
<button id="start">Start</button>
一時停止ボタンを簡単に作成できるようになりました。
<button id="stop">Stop</button>
これをスクリプトに追加します。
document.getElementById('stop').addEventListener('click', function() {
isRunning = false;
}, false);