我希望能够放大HTML 5画布中鼠标下方的点,例如Google Maps上的。我该如何实现?
终于解决了:
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>
关键是计算轴位置,以便缩放点(鼠标指针)在缩放后保持在同一位置。
最初,鼠标mouse/scale与角之间有一段距离,我们希望鼠标下方的点在缩放后保持在同一位置,但这是mouse/new_scale远离角的地方。因此,我们需要移动origin(角的坐标)以解决此问题。
mouse/scale
mouse/new_scale
origin
originx -= mousex/(scale*zoom) - mousex/scale; originy -= mousey/(scale*zoom) - mousey/scale; scale *= zoom
然后,其余代码需要应用缩放并转换到绘制上下文,以便其原点与画布角重合。