Reputation: 2551
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
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)
orfillRect(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:
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);
};
Upvotes: 1