栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

终于解决了:

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
(角的坐标)以解决此问题。

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432307.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号