LEATH
终于解决了它:var zoomIntensity = 0.2;var canvas = document.getElementById("canvas");var context = canvas.getContext("2d");var width = 600;var height = 200;var scale = 1;var originx = 0;var originy = 0;var visibleWidth = width;var visibleHeight = height;function draw(){
// Clear screen to white.
context.fillStyle = "white";
context.fillRect(originx,originy,800/scale,600/scale);
// Draw the black square.
context.fillStyle = "black";
context.fillRect(50,50,100,100);}// Draw loop at 60FPS.setInterval(draw, 1000/60);canvas.onwheel = function (event){
event.preventDefault();
// Get mouse offset.
var mousex = event.clientX - canvas.offsetLeft;
var mousey = event.clientY - canvas.offsetTop;
// Normalize wheel to +1 or -1.
var wheel = event.deltaY < 0 ? 1 : -1;
// Compute zoom factor.
var 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/scale角落一定距离,我们希望鼠标下方的点在缩放后保持在同一个位置,但这mouse/new_scale远离角落。因此,我们需要移动origin(角落的坐标)来解决这个问题。originx -= mousex/(scale*zoom) - mousex/scale;originy -= mousey/(scale*zoom) - mousey/scale;scale *= zomm然后剩下的代码需要应用缩放并转换为绘图上下文,因此它的原点与画布角一致。