放大点(使用缩放和平移)

2022-08-30 01:52:02

我希望能够在 HTML 5 画布中放大鼠标下方的点,就像在 Google 地图上放大一样。我怎样才能做到这一点?


答案 1

更好的解决方案是根据缩放的变化简单地移动视区的位置。缩放点只是旧缩放和新缩放中要保持不变的点。也就是说,预缩放的视口和后缩放的视口相对于视口具有相同的缩放点。鉴于我们正在相对于原点进行缩放。您可以相应地调整视口位置:

scalechange = newscale - oldscale;
offsetX = -(zoomPointX * scalechange);
offsetY = -(zoomPointY * scalechange);

所以实际上,当你放大时,你可以向下和向右平移,通过你放大的量,相对于你放大的点。

enter image description here


答案 2

终于解决了:

const zoomIntensity = 0.2;

const canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
const width = 600;
const height = 200;

let scale = 1;
let originx = 0;
let originy = 0;
let visibleWidth = width;
let visibleHeight = height;


function draw(){
    // Clear screen to white.
    context.fillStyle = "white";
    context.fillRect(originx, originy, width/scale, height/scale);
    // Draw the black square.
    context.fillStyle = "black";
    context.fillRect(50, 50, 100, 100);

    // Schedule the redraw for the next display refresh.
    window.requestAnimationFrame(draw);
}
// Begin the animation loop.
draw();

canvas.onwheel = function (event){
    event.preventDefault();
    // Get mouse offset.
    const mousex = event.clientX - canvas.offsetLeft;
    const mousey = event.clientY - canvas.offsetTop;
    // Normalize mouse wheel movement to +1 or -1 to avoid unusual jumps.
    const wheel = event.deltaY < 0 ? 1 : -1;

    // Compute zoom factor.
    const zoom = Math.exp(wheel * zoomIntensity);
    
    // Translate so the visible origin is at the context's origin.
    context.translate(originx, originy);
  
    // Compute the new visible origin. Originally the mouse is at a
    // distance mouse/scale from the corner, we want the point under
    // the mouse to remain in the same place after the zoom, but this
    // is at mouse/new_scale away from the corner. Therefore we need to
    // shift the origin (coordinates of the corner) to account for this.
    originx -= mousex/(scale*zoom) - mousex/scale;
    originy -= mousey/(scale*zoom) - mousey/scale;
    
    // Scale it (centered around the origin due to the trasnslate above).
    context.scale(zoom, zoom);
    // Offset the visible origin to it's proper position.
    context.translate(-originx, -originy);

    // Update scale and others.
    scale *= zoom;
    visibleWidth = width / scale;
    visibleHeight = height / scale;
}
<canvas id="canvas" width="600" height="200"></canvas>

正如@Tatarize所指出的,关键是要计算轴位置,以便缩放点(鼠标指针)在缩放后保持在同一位置。

最初鼠标距离角落有一段距离,我们希望鼠标下方的点在缩放后保持在同一位置,但这是远离角落的。因此,我们需要移动(角落的坐标)来解释这一点。mouse/scalemouse/new_scaleorigin

originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
scale *= zoom

然后,剩余的代码需要应用缩放并转换为绘制上下文,以便其原点与画布角重合。