放大点(使用比例和平移)我希望能够在HTML 5画布中放大鼠标下的点,例如放大Google地图。我怎样才能做到这一点?
3 回答
Helenr
TA贡献1780条经验 获得超3个赞
更好的解决方案是根据缩放的变化简单地移动视口的位置。缩放点只是旧缩放中的点和要保持不变的新缩放。也就是说视口预缩放和缩放后的视口相对于视口具有相同的缩放比例。鉴于我们相对于原点进行缩放。您可以相应地调整视口位置:
scalechange = newscale - oldscale;offsetX = -(zoomPointX * scalechange);offsetY = -(zoomPointY * scalechange);
因此,当您放大时,相对于您缩放的点,放大了多少,您可以放大和向右平移。
LEATH
TA贡献1936条经验 获得超6个赞
终于解决了它:
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
然后剩下的代码需要应用缩放并转换为绘图上下文,因此它的原点与画布角一致。
添加回答
举报
0/150
提交
取消