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); // https://stackoverflow.com/a/50233691 context.beginPath (); }
This is the HTML.
<canvas style='background-color:skyblue;' width="300" height="300" id="scribbler"> </canvas> <br> <form onsubmit='return false;'> <input type='submit' value='width' onclick='clear_canvas_width ()'> <input type='submit' value='rectangle' onclick='clear_canvas_rectangle ()'> </form>
Web links
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com) or use the discussion group at Google Groups.
/
Privacy /
Disclaimer