Sora
Sora

Reputation: 2551

animate a circle inside a canvas

I'm trying to animate a circle inside an html5 canvas but I'm having trouble when updating this circle AKA erasing the old position and drawn the new position my jsfiddle:

As you can see the clear function is not clearing the entire circle but it's making it's color lighter is there anyway to clear the old circle without clearing the whole canvas or clearing a small rectangle that contain the circle ?

        var clearCircle = function (c) {
            ctx.save();
            ctx.globalCompositeOperation = 'destination-out';
            ctx.beginPath();
            ctx.arc(c.x, c.y, c.r, 0, 2 * Math.PI, false);
            ctx.fill();
            ctx.restore();
        };

Upvotes: 1

Views: 164

Answers (2)

user1693593
user1693593

Reputation:

You can simply change your composite mode to copy and move it globally. This will erase everything but will limit you to one draw operation.

Modified fiddle using copy composite mode.

The more correct way is to use either:

  • clearRect(x, y, w, h) or
  • fillRect(x, y, w, h)

the latter in case you need a background color. You can also use drawImage(img, x, y) if you want to fill the background with an image.

All of these methods (except composite mode) allow you to only draw the region that is necessary to update:

  • Store the current position of the circle
  • On next update, clearRect/fillRect etc. that position and width and height of circle. Add a pixel or two to the size to catch anti-aliased pixels (x - 1, y - 1, w + 2, h + 2).
  • Draw the new circle and repeat:

Adjust this function to adopt:

var clearCircle = function (c) {
    ctx.clearRect(c.x - c.r - 1, c.y - c.r - 1, c.r*2+2, c.r*2+2);
};

Modified fiddle

Upvotes: 1

A1rPun
A1rPun

Reputation: 16847

Add this to your updateCanvas method:

ctx.clearRect(0,0,cw,ch);

jsfiddle

Upvotes: 0

Related Questions