Blog Archive

HTML5 Clear canvas context example

Let's say the canvas element defined in your HTML page is
    <canvas id="myCanvasPanel" width="600" height="300">no canvas support</canvas>

First get reference to your canvas 2d context
    var myCanvas = document.getElementById("myCanvasPanel");
    var    myCanvasContext = myCanvas.getContext('2d');


Then you can use either of these methods to clear a canvas element
  • myCanvasContext.clearRect(0, 0, canvas.width, canvas.height)
  • myCanvasContext.width = myCanvasContext.width;
      
Setting the canvas width to itself not only clears the canvas, it clears all canvas state such as
transformations, lineWidth, strokeStyle, font, textAlign, etc. clearRect works properly as long as
you haven't modfied the transformation matrix. If you have custom transformation matrix then you must
save the current state first then restore it back. Here is how to do it.
//save the current transformation matrix state
myCanvasContext.save();
//set the transformation matrix to its default state 
myCanvasContext.setTransform(1, 0, 0, 1, 0, 0);
//clear the canvas here
myCanvasContext.clearRect(0, 0, canvas.width, canvas.height);
//restore the last saved transformation matrix state
myCanvasContext.restore();