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>
Clear
rectangleid
with "mycanvas"
, width with "300" and height as "180"id
as clear
and value with cleardocument.getElementById (clear)
- It defines the id
of the button as clear
which calls the function in to the buttonaddEventlistener, ('click',function()),
false calls the function to clear the rectangle with the given values output
Views: 14281 | Post Order: 46