HTML5 > Canvas

Clear Canvas in HTML5

How to clear the canvas in HTML5?


Clear Canvas is used to clear the canvas, In order to clear the canvas we use ClearRect(), it is used to reset or clear the width and height of the canvas 

 <h2 style="color:green">Press the button to clear the canvas rectangle</h2>
    <canvas id="myCanvas" width="300" height="180"></canvas>
        <input type="button" id="clear" value="Clear">
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        context.rect(18, 50, 200, 100);
        context.fillStyle = "red";
        context.lineWidth = "20";
        context.strokeStyle = "pink";
        document.getElementById('clear').addEventListener('click', function () {
            context.clearRect(0, 0, canvas.width, canvas.height);
        }, false);
  • In the above code snippet we have defined the Clear rectangle
  • We are having the canvas element as id  with "mycanvas", width with "300" and height as "180"
  • We are having button with id as clear and value with clear
  • In the next line we have created the rectangle by using values  
  • The document.getElementById (clear)- It defines the id of the button as clear which calls the function in to the button
  • addEventlistener, ('click',function()), false  calls the function to clear the rectangle with the given values    


 Views: 592 | Post Order: 46

Write for us