HTML5 Delete Previous Drawn Object in Canvas

I have a polygon object (say, a car) drawn inside an HTML5 canvas using the moveTo and lineTo . I want to draw this object many times in different positions on the canvas (simulating a moving object). My problem is that the previous object is not cleared. Instead, several images are drawn on the canvas. How can I fix this problem?

+6
source share
2 answers

Canvases are just arrays of pixels; they don’t know anything about the shapes you painted.

There are animated tricks that were previously used on raster displays (for example, "xor drawing"), which can be used to delete an old figure before you draw a new one, but on modern machines it is much simpler (and very fast) to just erase the canvas and start again for each frame.

Given your comments on the other answers, I would suggest just using two canvases - one for a static background and one for a car. If the background image is static, it may even be an <img> element instead of a Canvas.

If the car’s image is static, you can also just draw it once, and then use CSS positioning to set its position relative to the background for each frame.

+9
source

You must clear the canvas at the beginning of each frame of the frame.

 context.clearRect(0, 0, canvas.width, canvas.height); 
+8
source

Source: https://habr.com/ru/post/946714/


All Articles