HTML5 > Canvas

Clear Canvas in HTML5

How to clear the canvas in HTML5?


ClearCanvas

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>
    <div>
        <input type="button" id="clear" value="Clear">
    </div>
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        context.beginPath();
        context.rect(18, 50, 200, 100);
        context.fillStyle = "red";
        context.fill();
        context.lineWidth = "20";
        context.strokeStyle = "pink";
        context.stroke();
        document.getElementById('clear').addEventListener('click', function () {
            context.clearRect(0, 0, canvas.width, canvas.height);
        }, false);
    </script>
  • 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    

output

 Views: 14281 | Post Order: 46



Write for us






Hosting Recommendations