简体   繁体   中英

HTML5 Remove previous drawn object in canvas

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 different positions in the canvas (simulating a moving object). My problem is that the previous drawn object is not getting cleared. Instead, multiple images are drawn on the canvas. How can I fix this issue?

您必须在每个并条框开始时清除画布

context.clearRect(0, 0, canvas.width, canvas.height);

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 (eg "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.

suppose your shape is car then you first have to assign a new graphic like:

car.graphics = new createjs.Graphics();

car.graphics
            .setStrokeStyle(1)
            .beginStroke("#000000")
            .moveTo()
            .lineTo()
            .lineTo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM