乐闻世界logo
搜索文章和话题

How to Image zoom centered on mouse position

1个答案

1

Implementing image scaling centered on the mouse position in HTML's <canvas> element can be broken down into several steps. Below, I will explain each step in detail and provide code examples for clarity.

Step 1: Capture Mouse Position

First, we need to obtain the mouse position on the canvas. This can be achieved by listening to mousemove or mousewheel events.

javascript
let canvas = document.getElementById('myCanvas'); let ctx = canvas.getContext('2d'); let mouseX = 0; let mouseY = 0; canvas.addEventListener('mousemove', function(e) { mouseX = e.offsetX; mouseY = e.offsetY; });

Step 2: Scale the Image

In the mouse wheel event, we can determine whether to zoom in or out based on the direction of the scroll.

javascript
let scale = 1; const scaleFactor = 1.1; // Scale factor for zooming in or out canvas.addEventListener('wheel', function(e) { e.preventDefault(); // Prevent page scrolling if (e.deltaY < 0) { // Zoom in scale *= scaleFactor; } else { // Zoom out scale /= scaleFactor; } redrawCanvas(); });

Step 3: Scale Around the Mouse Position

To implement scaling centered on the mouse, we need to adjust the canvas's origin so that the mouse position is at the center before applying the scale transformation. This is achieved by modifying the canvas's translate property.

javascript
function redrawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear previous frame ctx.save(); // Save current drawing state ctx.translate(mouseX, mouseY); // Move canvas origin to mouse position ctx.scale(scale, scale); // Apply scaling ctx.translate(-mouseX, -mouseY); // Restore canvas origin ctx.drawImage(image, 0, 0, canvas.width, canvas.height); // Redraw image ctx.restore(); // Restore previous drawing state }

In the above code, the redrawCanvas function first clears the canvas, saves the current state, adjusts the canvas's translate and scale properties, and then redraws the image.

The above steps demonstrate how to implement image scaling centered on the mouse position in HTML canvas. The key is to accurately capture the mouse position and adjust the canvas's translate and scale properties during scaling. This method can be applied to various graphics processing applications to enhance user interaction.

2024年6月29日 12:07 回复

你的答案