- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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

Click the Clear Canvas button and the canvas will clear −

- Related Articles
- How to clear Tkinter Canvas?
- How to clear a chart from HTML5 canvas so that hover events cannot be triggered?
- How to clear the EEPROM with Arduino?
- How to clear Python shell?
- How to copy the content of one HTML5 Canvas to another Canvas locally?
- Properties for HTML5 Canvas to create shadows
- How to clear the global variables in Postman?
- How to clear console in C?
- How to clear screen using python?
- How to clear console in MongoDB?
- How to clear ArrayBlockingQueue in android?
- How to clear screen using C#?
- How to clear screen in python?
- How to clear screen using Java?
- How to clear a MongoDB database?

Advertisements