How to Clear the Canvas for Redrawing?


To clear the canvas for redrawing, use the canvas.clearRect() method in HTML. It clears the specified pixels. The parameters of the method includes −

  • x − The x-coordinate to clear
  • y − The y-coordinate to clear
  • width − The width of the rectangle to clear
  • height − The height of the rectangle to clear

Let us see an example to create a canvas and clear it on the click of a button for redrawing in JavaScript. Here’s our canvas code that creates a canvas −

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeRect(5, 5, 25, 15);
ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15);

The clear button code in JavaScript. The canvas is cleared usung the clearRect() method −

var button=document.getElementById("clear");
button.onclick=function clearcanvas(){
   ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
   var w = myCanvas.width;
   myCanvas.width = 1;
   myCanvas.width = w;
}

The button code in HTML −

<button id="clear" type="button">Clear Canvas</button>

Example

Let us now see the complete example to clear the canvas −

<!DOCTYPE html>
<html>
<body>
   <button id="clear" type="button">Clear Canvas</button>
   <canvas id="myCanvas" width="300" height="170" style="border:1px solid #d3d3d3;"></canvas>
   <script>
      var c = document.getElementById("myCanvas");
      var ctx = c.getContext("2d");
      ctx.strokeRect(5, 5, 25, 15);
      ctx.scale(2, 2);
      ctx.strokeRect(5, 5, 25, 15);
      var button=document.getElementById("clear");
      button.onclick=function clearcanvas(){
         ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
         var w = myCanvas.width;
         myCanvas.width = 1;
         myCanvas.width = w;
      }
   </script> 
</body>
</html>

Output

Click the Clear Canvas button and the canvas will clear −

Updated on: 21-Nov-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements