Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the canvas for redrawing

After experimenting with composite operations and drawing images on the canvas I'm now trying to remove images and compositing. How do I do this?

I need to clear the canvas for redrawing other images; this can go on for a while so I don't think drawing a new rectangle every time will be the most efficient option.

like image 989
richard Avatar asked Jan 26 '10 20:01

richard


People also ask

Which method is used to clear the canvas?

The clearRect() method in HTML canvas is used to clear the pixels in a given rectangle.

How do you erase a picture on canvas?

You can easily clear you canvas by resetting its width and height. For example: canvas. width = canvas. width should clear your drawing context.


2 Answers

Use: context.clearRect(0, 0, canvas.width, canvas.height);

This is the fastest and most descriptive way to clear the entire canvas.

Do not use: canvas.width = canvas.width;

Resetting canvas.width resets all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.), it is very slow (compared to clearRect), it doesn't work in all browsers, and it doesn't describe what you are actually trying to do.

Dealing with transformed coordinates

If you have modified the transformation matrix (e.g. using scale, rotate, or translate) then context.clearRect(0,0,canvas.width,canvas.height) will likely not clear the entire visible portion of the canvas.

The solution? Reset the transformation matrix prior to clearing the canvas:

// Store the current transformation matrix context.save();  // Use the identity matrix while clearing the canvas context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, canvas.width, canvas.height);  // Restore the transform context.restore(); 

Edit: I've just done some profiling and (in Chrome) it is about 10% faster to clear a 300x150 (default size) canvas without resetting the transform. As the size of your canvas increases this difference drops.

That is already relatively insignificant, but in most cases you will be drawing considerably more than you are clearing and I believe this performance difference be irrelevant.

100000 iterations averaged 10 times: 1885ms to clear 2112ms to reset and clear 
like image 38
Prestaul Avatar answered Sep 29 '22 14:09

Prestaul


Given that canvas is a canvas element or an OffscreenCanvas object,

const context = canvas.getContext('2d');  context.clearRect(0, 0, canvas.width, canvas.height); 
like image 132
Pentium10 Avatar answered Sep 29 '22 13:09

Pentium10