Learn how to use JavaScript Canvas clearHitRegions method effectively with examples and detailed explanations. Enhance your web development skills with this step-by-step tutorial.
last modified April 3, 2025
In this article, we explore the Canvas clearHitRegions method in JavaScript. This method is essential for managing interactive regions on HTML canvas. Mastering hit regions is crucial for creating interactive graphics.
Hit regions are areas on canvas that can respond to user interactions like clicks or touches. The clearHitRegions method removes all defined hit regions from the canvas. This helps manage dynamic interactive elements.
The main hit region methods are addHitRegion, removeHitRegion, and clearHitRegions. These work with path-drawing methods to create interactive canvas elements.
This example demonstrates how to clear all hit regions from a canvas.
index.html
<!DOCTYPE html> <html> <head> <title>Basic clearHitRegions</title> </head> <body>
<canvas id=“myCanvas” width=“300” height=“200”></canvas>
<script> const canvas = document.getElementById(‘myCanvas’); const ctx = canvas.getContext(‘2d’);
// Add a hit region
ctx.beginPath();
ctx.rect(50, 50, 100, 100);
ctx.addHitRegion({id: 'square'});
// Clear all hit regions
ctx.clearHitRegions();
</script>
</body> </html>
In this basic example, we create a canvas element and get its 2D context. We add a rectangular hit region with ID ‘square’ to the canvas.
The clearHitRegions method removes all hit regions from the canvas. This is useful when you need to reset interactive areas completely.
This example shows how to manage hit regions dynamically with clearHitRegions.
index.html
<!DOCTYPE html> <html> <head> <title>Dynamic Hit Regions</title> </head> <body>
<canvas id=“myCanvas” width=“300” height=“200”></canvas> <button id=“clearBtn”>Clear Regions</button>
<script> const canvas = document.getElementById(‘myCanvas’); const ctx = canvas.getContext(‘2d’); const clearBtn = document.getElementById(‘clearBtn’);
// Add multiple hit regions
function addRegions() {
ctx.beginPath();
ctx.rect(20, 20, 80, 80);
ctx.addHitRegion({id: 'region1'});
ctx.beginPath();
ctx.rect(120, 20, 80, 80);
ctx.addHitRegion({id: 'region2'});
}
// Clear button handler
clearBtn.addEventListener('click', () => {
ctx.clearHitRegions();
console.log('All hit regions cleared');
});
addRegions();
</script>
</body> </html>
Here we create two rectangular hit regions and a button to clear them. The addRegions function defines two distinct hit regions.
When the button is clicked, clearHitRegions removes all hit regions. This pattern is useful for dynamic UIs where regions change often.
This example demonstrates clearHitRegions in a simple game scenario.
index.html
<!DOCTYPE html> <html> <head> <title>Game Hit Regions</title> </head> <body>
<canvas id=“gameCanvas” width=“400” height=“300”></canvas>
<script> const canvas = document.getElementById(‘gameCanvas’); const ctx = canvas.getContext(‘2d’); let score = 0;
function createTarget(x, y) {
ctx.beginPath();
ctx.arc(x, y, 30, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.addHitRegion({
id: 'target',
cursor: 'pointer'
});
}
function resetGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearHitRegions();
createTarget(
Math.random() * (canvas.width - 60) + 30,
Math.random() * (canvas.height - 60) + 30
);
}
canvas.addEventListener('click', (e) => {
const region = e.region;
if (region === 'target') {
score++;
console.log('Score:', score);
resetGame();
}
});
resetGame();
</script>
</body> </html>
This creates a simple game where clicking red targets increases score. Each target is a circular hit region that responds to clicks.
The resetGame function uses clearHitRegions to remove old targets before creating new ones. This ensures clean interaction.
This example shows managing different types of hit regions with clearHitRegions.
index.html
<!DOCTYPE html> <html> <head> <title>Multiple Region Types</title> </head> <body>
<canvas id=“myCanvas” width=“400” height=“300”></canvas> <button id=“resetBtn”>Reset All Regions</button>
<script> const canvas = document.getElementById(‘myCanvas’); const ctx = canvas.getContext(‘2d’); const resetBtn = document.getElementById(‘resetBtn’);
function setupRegions() {
// Button region
ctx.beginPath();
ctx.rect(50, 50, 100, 50);
ctx.fillStyle = '#4CAF50';
ctx.fill();
ctx.addHitRegion({
id: 'greenBtn',
cursor: 'pointer'
});
// Draggable region
ctx.beginPath();
ctx.arc(300, 100, 40, 0, Math.PI * 2);
ctx.fillStyle = '#2196F3';
ctx.fill();
ctx.addHitRegion({
id: 'draggable',
cursor: 'move'
});
}
resetBtn.addEventListener('click', () => {
ctx.clearHitRegions();
setupRegions();
console.log('Regions reset');
});
canvas.addEventListener('click', (e) => {
if (e.region === 'greenBtn') {
alert('Button clicked!');
}
});
setupRegions();
</script>
</body> </html>
This example creates two distinct hit regions with different behaviors. A green button region shows alerts, while a blue circle is draggable.
The reset button uses clearHitRegions to remove all regions before recreating them. This pattern is useful for complex interfaces.
This example demonstrates advanced hit region lifecycle management.
index.html
<!DOCTYPE html> <html> <head> <title>Advanced Region Management</title> </head> <body>
<canvas id=“appCanvas” width=“500” height=“400”></canvas> <div> <button id=“addBtn”>Add Region</button> <button id=“clearBtn”>Clear Regions</button> <span id=“counter”>Regions: 0</span> </div>
<script> const canvas = document.getElementById(‘appCanvas’); const ctx = canvas.getContext(‘2d’); const addBtn = document.getElementById(‘addBtn’); const clearBtn = document.getElementById(‘clearBtn’); const counter = document.getElementById(‘counter’); let regionCount = 0;
function addRandomRegion() {
const x = Math.random() * (canvas.width - 80) + 40;
const y = Math.random() * (canvas.height - 80) + 40;
const size = Math.random() * 30 + 20;
const hue = Math.floor(Math.random() * 360);
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fillStyle = `hsl(${hue}, 70%, 60%)`;
ctx.fill();
const regionId = `region-${regionCount}`;
ctx.addHitRegion({
id: regionId,
cursor: 'pointer'
});
regionCount++;
counter.textContent = `Regions: ${regionCount}`;
}
function clearAllRegions() {
ctx.clearHitRegions();
ctx.clearRect(0, 0, canvas.width, canvas.height);
regionCount = 0;
counter.textContent = `Regions: ${regionCount}`;
}
addBtn.addEventListener('click', addRandomRegion);
clearBtn.addEventListener('click', clearAllRegions);
canvas.addEventListener('click', (e) => {
if (e.region) {
console.log(`Clicked region: ${e.region}`);
}
});
</script>
</body> </html>
This advanced example shows dynamic hit region creation and management. Users can add random circular regions and clear them completely.
The clearAllRegions function uses clearHitRegions along with clearRect to reset the canvas completely. This shows comprehensive region lifecycle management.
MDN clearHitRegions Documentation
In this article, we have explored various techniques for managing hit regions on HTML canvas using clearHitRegions. Mastering these methods is essential for creating interactive canvas applications.
My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.
List all JS Canvas tutorials.