HTML5 Remove previous drawn object in canvas

后端 未结 2 1503
刺人心
刺人心 2020-12-17 19:01

I have a polygon object (say a car) drawn inside a HTML5 canvas with help of methods moveTo and lineTo. I want to repeatedly draw that object at di

相关标签:
2条回答
  • 2020-12-17 19:17

    You have to clear the canvas at the start of every draw frame

    context.clearRect(0, 0, canvas.width, canvas.height);
    
    0 讨论(0)
  • 2020-12-17 19:22

    Canvases are just arrays of pixels, they know nothing of the shapes you have drawn.

    There are animation tricks that used to be used on bitmapped displays (e.g. "xor drawing") that can be used to remove the old shape before you draw the new one, but on modern machines it's generally far simpler (and perfectly fast) to just erase the canvas and start again for each frame.

    Given your comments to other answers, I'd suggest just using two Canvases - one for the static background and one for the car. If the background image is static it could even be an <img> element instead of a Canvas.

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

    0 讨论(0)
提交回复
热议问题