html5-canvas Rectangles


You can use the clearRect method to clear any rectangular section of the canvas.

// Clear the entire canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);

Note: clearRect is dependent on the transformation matrix.

To deal with this, it's possible to reset the transformation matrix before you clear the canvas.;                                       // Save the current context state
ctx.setTransform(1, 0, 0, 1, 0, 0);               // Reset the transformation matrix
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.restore();                                    // Revert context state including 
                                                  // transformation matrix

Note: and ctx.restore are only requiered if you wish to keep the canvas 2D context state. In some situations save and restore can be be slow and generally should be avoided if not required.