Tell me how to realize the appearance of an object (red square) via setTimeout ()
I implemented it differently, but for some reason it seems that it is not right, or does such a solution take place?
var canvas = document.getElementById("d1"); var ctx = canvas.getContext("2d"); var pressedLeft = false; var pressedRight = false; var pressedUp = false; var pressedBottom = false; document.addEventListener("keydown", keyDown, false); document.addEventListener("keyup", keyUp, false); function keyDown(e) { if(e.keyCode == 37) { pressedLeft = true; } else if(e.keyCode == 39) { pressedRight = true; } else if(e.keyCode == 38) { pressedUp = true; } else if(e.keyCode == 40) { pressedBottom = true; } } function keyUp(e) { if(e.keyCode == 37) { pressedLeft = false; } else if(e.keyCode == 39) { pressedRight = false; } else if(e.keyCode == 38) { pressedUp = false; } else if(e.keyCode == 40) { pressedBottom = false; } } var player = { x: 10, y: 10, pW: 130, pH: 130, draw: function() { ctx.beginPath(); ctx.rect(this.x, this.y, this.pW, this.pH); ctx.fillStyle = "black"; ctx.fill(); ctx.closePath(); } } var box = { x: 5, y: 5, bW: 140, bH: 140, timer: 0, draw: function() { ctx.beginPath(); ctx.rect(this.x, this.y, this.bW, this.bH); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); } } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); box.timer++; if(box.timer >= 150) { box.draw(); } player.draw(); if(pressedRight) { player.x = 162; } if(pressedLeft) { player.x = 10; } if(pressedUp) { player.y = 10; } if (pressedBottom) { player.y = 162; } } setInterval(draw, 1000/60); #d1 { border: 3px solid black; background: #fff url('http://jscoder.ru/bg1.jpg'); } <canvas id="d1" width="300" height="300"></canvas>