Michael Lewis
Michael Lewis

Reputation: 4302

Why does canvas re-render the entire canvas rather than only a specific portion?

From my very limited html5 canvas experience, it seems like the way to animate something is to clear the entire canvas, and draw everything from scratch.

This doesn't seem very performant. I'm wondering why this was the chosen approach?

Is there an alternative? For example, using an object-oriented approach, if you wanted to re-render a tree in the foreground, the system should cache the background, and only rerender that layer.

Upvotes: 2

Views: 603

Answers (2)

5260452
5260452

Reputation: 11600

That's the basic technique, yes. You could also clear a specific area of the canvas instead, using clearRect():

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Drawing_shapes

// Clear the specified rectangular area from x, y through width, height.
context.clearRect(x, y, width, height);

In your case of change foregrounds and backgrounds, however, consider modifying the globalCompositeOperation, which enables you to draw shapes under existing shapes:

// Draw new shapes behind the existing canvas content.
ctx.globalCompositeOperation = 'destination-over';

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing

Another useful method is clip(), which allows you to draw shapes as masks:

// Create a circular clipping path.
ctx.beginPath();
ctx.arc(0, 0, 60, 0, Math.PI * 2, true);
ctx.clip();

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing

Upvotes: 1

markE
markE

Reputation: 105015

Your understanding is correct.

Typical canvas apps will completely erase the canvas and redraw objects.

This process works well because Html Canvas is designed with blazingly fast drawing speed.

Unlike object oriented design, the data that draws on the canvas has been completely "flattened".

There is a single data array containing the Red, Green, Blue & Alpha components of all pixels on the canvas.

[ 
    pixel1Red, pixel1Green, pixel1Blue, pixel1Alpha,
    pixel2Red, pixel2Green, pixel2Blue, pixel2Alpha,
    pixel3Red, pixel3Green, pixel3Blue, pixel3Alpha,
    ...
]

This means that any color component of any pixel can be accessed with a single jump.

This flat structure also means that if an image needs to be drawn on the canvas, the browser only needs to copy sequential data from the source image directly into sequential data in the canvas pixel array.

In addition, Canvas is hardware accelerated when a GPU is available.

Upvotes: 1

Related Questions