Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Zoom HTML5 Canvas to Mouse Cursor
The HTML5 Canvas API provides powerful methods to zoom content toward a specific point, such as the mouse cursor. By default, the canvas scales from its origin at [0,0], but you can change this behavior using coordinate transformations.
Understanding Canvas Transformations
The translate() method moves the canvas origin to a new position, while scale() resizes the drawing context. To zoom toward the mouse cursor, you need to combine these transformations in a specific sequence.
The Zoom Algorithm
To zoom toward a specific point (like mouse coordinates), follow these three steps:
ctx.translate(pt.x, pt.y); // Move origin to zoom point ctx.scale(factor, factor); // Apply zoom factor ctx.translate(-pt.x, -pt.y); // Move origin back
Complete Zoom Implementation
<canvas id="myCanvas" width="400" height="300" style="border: 1px solid black;"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw initial content
function drawContent() {
ctx.clearRect(-canvas.width, -canvas.height, canvas.width * 3, canvas.height * 3);
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
ctx.fillStyle = 'red';
ctx.fillRect(200, 100, 80, 80);
ctx.strokeStyle = 'green';
ctx.strokeRect(100, 150, 120, 60);
}
// Initial draw
drawContent();
// Zoom function
function zoomToPoint(mouseX, mouseY, zoomFactor) {
ctx.translate(mouseX, mouseY);
ctx.scale(zoomFactor, zoomFactor);
ctx.translate(-mouseX, -mouseY);
drawContent();
}
// Mouse event handler
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1; // Zoom out/in
zoomToPoint(mouseX, mouseY, zoomFactor);
});
console.log("Scroll mouse wheel over the canvas to zoom");
</script>
How It Works
The transformation sequence works as follows:
- Translate to mouse point: Moves the canvas origin to the mouse coordinates
- Apply scale: Scales the canvas from the new origin (mouse position)
- Translate back: Restores the coordinate system while keeping the zoom effect
Key Parameters
| Parameter | Description | Example |
|---|---|---|
| pt.x, pt.y | Mouse cursor coordinates | 200, 150 |
| factor | Zoom scale (1.0 = no change) | 1.2 (zoom in), 0.8 (zoom out) |
Conclusion
By combining translate() and scale() transformations in the correct sequence, you can zoom the canvas toward any point, creating an intuitive zoom-to-cursor effect. This technique is essential for interactive canvas applications.
