简体   繁体   中英

How to clear an element of canvas that is moving (leaves a streak) without clearing canvas

Say I have drawn a circle on a canvas that has something else drawn on it that stops me from clearing the canvas - due to the other element being randomly generated

var circleX = 50;
var circleY = 10;
var moveCircX = 2;
var moveCircY = 3;
function createCirc(){
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(circleX, circleY, 10, 0, Math.PI*2, true);
    ctx.fill();

}
function circMove(){
    circleY = (circleY + circMoveY)
//then validation to stop it from being drawn of the canvas

So what I'm trying to do is move the circle but clear the previous drawn circle from the canvas. So is there a solution to clearing the circle or would it be easier to create a sprite that replicates the circle?

Since your background isn't changing, the simplest strategy is to copy the background before you first draw your circle, then draw your circle. When you're moving, redraw that part of the background from the copy you kept, then draw your circle in the new place.

An efficient way to do that is to use getImageData and putImageData .

So, (my javascript is rusty, so this may not be perfect. Feel free to correct any mistakes), before the first time you createCirc , simply do:

imageData = ctx.getImageData(0,0, ctx.canvas.width, ctx.canvas.height)

And, in your circMove function, before you move and redraw the circle, you want:

ctx.putImageData(imageData, circleX, circleY, circleX, circleY, 2*circle_radius, 2*circle_radius)

(You don't define circle_radius , but I'm sure you must have a similar value. I'm using 2x the radius to presumably be the size of the image that is drawn.)

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