![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
![](https://www.tutorialspoint.com/assets/questions/media/495676-1670231199.png)
Click the Clear Canvas button and the canvas will clear −
![](https://www.tutorialspoint.com/assets/questions/media/495676-1670231220.png)
Advertisements