Hello. It is necessary to draw with the help of Canvas and JavaScript animation of the falling primitive. So here. How to make it so that it does not leave the previous state?

Code snippet

var ctx = document.querySelector("canvas").getContext('2d'); ctx.lineWidth = 2; function draw() { var y = 0; function frame() { ctx.beginPath(); ctx.arc(100, 100+y, 20, 0, 2*3.14); ctx.stroke(); ctx.fill(); ctx.closePath(); y+=5; if (y >= 100) clearTimeout(timer); } var timer = setInterval(frame, 50); } draw(); 
 <canvas width=200 height=200> </canvas> 

I can provide all the code if necessary. What happened:

The result of the work.

  • setInterval ... clearTimeout - bug. - Qwertiy
  • @Qwertiy can be more? - Desmond Fox
  • This is off topic bug. And on the topic - you need to clear everything rendered and draw again. Or use the save method and restore it. - Qwertiy
  • @Qwertiy How can you save and restore? ctx.save(); ctx.restore() ctx.save(); ctx.restore() ? - Desmond Fox
  • Not. This pair saves the context settings, but not the drawing. There is another. - Qwertiy

1 answer 1

The getImageData method allows to remember the displayed image, and putImageData - to restore it:

 ~function () { var canvas = document.querySelector("canvas"); var ctx = canvas.getContext('2d'); ctx.lineWidth = 2; function draw() { var y = 0; ctx.fillStyle = 'red'; ctx.fillRect(20, 20, 150, 100); var state = ctx.getImageData(0, 0, canvas.width, canvas.height); function frame() { ctx.putImageData(state, 0, 0); ctx.beginPath(); ctx.fillStyle = 'blue'; ctx.arc(100, 100+y, 20, 0, 2*3.14); ctx.stroke(); ctx.fill(); ctx.closePath(); y+=5; if (y >= 100) clearInterval(timer); } var timer = setInterval(frame, 50); } draw(); }(); 
 canvas { border: 1px dotted green; } 
 <canvas width=200 height=230> </canvas> 

  • It seems everything works with this code. Thank. - Desmond Fox