How to clear a <canvas>

This page demonstrates two ways to clear a canvas. The first is based on changing the width of the element. The second uses the clearRect method of the canvas context. Try them by drawing something in the canvas below and then pressing either one of the buttons to clear it again.

The following are the JavaScript routines. This page also uses the JavaScript described in A simple scribbler using <canvas>.

function clear_canvas_width ()
    var s = document.getElementById ("scribbler");
    var w = s.width;
    s.width = 10;
    s.width = w;

function clear_canvas_rectangle ()
    context.clearRect (0, 0, 300, 300);
    context.beginPath ();

This is the HTML.

<canvas style='background-color:skyblue;'
        width="300" height="300"
<form onsubmit='return false;'>
<input type='submit' value='width' onclick='clear_canvas_width ()'>
<input type='submit' value='rectangle' onclick='clear_canvas_rectangle ()'>

Web links

Copyright © Ben Bullock 2009-2021. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. News about the site. / Privacy / Disclaimer