Veera
Veera

Reputation: 33202

Why is the HTML5 canvas not clearing in my code?

I am just getting started with Canvas programming and trying to build a small game. Below is a sample code that I am trying out. My intention is to:

  1. Create a canvas.
  2. Fill it with some background color.
  3. Draw a circle.
  4. Clear the canvas.
  5. Draw another circle in different location.

Here's the code:

var canvas = document.createElement('canvas');
canvas.width= 400;
canvas.height = 400;
document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');

// 2. Fill background
ctx.fillStyle = 'rgb(30,0,0)';
ctx.fillRect(0,0,400,400);

// 3. Draw circle
ctx.save();
ctx.fillStyle = 'rgba(256,30,30,.8)';
ctx.arc(50,50, 20, 0, Math.PI*2, true);
ctx.fill();
ctx.restore();

// 4. Clear Canvas
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();

// 5. Draw another circle
ctx.save();
ctx.fillStyle = 'rgba(256,30,30,.8)';
ctx.arc(150,150, 20, 0, Math.PI*2, true);
ctx.fill();
ctx.restore();

But as you can see, only the background color gets cleared and the first circle remains as it is.

Why is the above code fails to clear the canvas completely before drawing second circle?

Upvotes: 1

Views: 140

Answers (1)

GameAlchemist
GameAlchemist

Reputation: 19294

If you don't use beginPath before starting a new path, all draw command keeps stacking in the current path.

What's happening here is that when you fill() the second time, the first circle is still in the current path, so even if the screen was in deed cleared, there are two circles drawn with this single fill() command.

==>> use beginPath() before starting a new path.

Upvotes: 1

Related Questions