To clear a canvas element in JavaScript, you can use the clearRect
method of the canvas’s 2D rendering context.
// Get the canvas's 2D rendering context
const ctx = canvas.getContext('2d');
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
Code language: JavaScript (javascript)
This will clear the entire canvas by replacing all the pixels with transparent pixels.
If you instead want to clear the canvas with a specific color, you could use fillRect
:
// Get the canvas's 2D rendering context
const ctx = canvas.getContext('2d');
// Set the fill style for the rectangle
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
Code language: JavaScript (javascript)
This draws a white rectangle over the entire canvas.
Example With Button
<!-- HTML for the canvas element and buttons -->
<canvas id="myCanvas" style="display:block;"></canvas>
<button id="clearButton">Clear Canvas</button>
<button id="addRectangleButton">Add Rectangle</button>
<script>
// Get references to the canvas and button elements
const canvas = document.getElementById('myCanvas');
const clearButton = document.getElementById('clearButton');
const addRectangleButton = document.getElementById('addRectangleButton');
// Set the canvas size
canvas.width = 500;
canvas.height = 200;
// Get the canvas's 2D rendering context
const ctx = canvas.getContext('2d');
// Add an event listener for the clear button click
clearButton.addEventListener('click', function() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
// Add an event listener for the add rectangle button click
addRectangleButton.addEventListener('click', function() {
// Generate random coordinates and dimensions for the rectangle
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const width = Math.random() * canvas.width;
const height = Math.random() * canvas.height;
// Set the fill style to white
ctx.fillStyle = '#ffffff';
// Draw the rectangle at the random coordinates with the random dimensions
ctx.fillRect(x, y, width, height);
});
</script>
Code language: HTML, XML (xml)
When the button is clicked, the clearRect
method is called with the coordinates (0, 0) and the width and height of the canvas.
Demo
The demo below runs the previous code so you can see it in action. Click “Add Rectangle” first and then try clearing the canvas.
Leave a Reply