图像变焦以鼠标位置为中心 [英] Image zoom centered on mouse position

查看:140
本文介绍了图像变焦以鼠标位置为中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Fabric.js编写脚本,以便在当前鼠标位置缩放图像。我已经取得了一些进展,但在某个地方有一个错误。

I am writing a script with Fabric.js to zoom an image at the current mouse position. I have made some progress but there is an error somewhere.

案例1 :保持鼠标在一点,用鼠标滚轮缩放。

Case 1: Keep the mouse at one point and zoom with the mouse wheel.

结果:图片缩放特定像素。

Result: Works perfectly, image zooms at that particular pixel.

strong>在一个位置放大一点(鼠标滚轮的3-5倍),然后将鼠标移动到新位置并放大。

Case 2: Zoom in a little at one position (3-5 times with mouse wheel), then move the mouse to a new position and zoom in there.

结果:Works

我的代码在这个小提琴:

My code is in this fiddle:

https://jsfiddle.net/gauravsoni/y3w0yx2m/1/

我怀疑图片定位逻辑有问题:

I suspect there is something wrong with the image positioning logic:

imgInstance.set({top:imgInstance.getTop()-newMousY,left:imgInstance.getLeft()-newMousX});

出现了什么问题?

推荐答案

解决这个难题的关键是了解图像如何放大。如果我们使用1.2的缩放系数,图片将变大20%。我们将1.2分配给变量 factor 并执行以下操作:

The key to solving this puzzle is to understand how the image gets enlarged. If we're using a zoom factor of 1.2, the image becomes 20% larger. We assign 1.2 to the variable factor and do the following:

image.setScaleX(image.getScaleX() * factor);
image.setScaleY(image.getScaleY() * factor);

图片的左上角在放大图片时保持在同一位置。现在考虑鼠标光标下的点。光标上方和左侧的每个像素已经变大了20%。这会将光标下的点向下和向右移动20%。同时,光标位于相同的位置。

The upper left corner of the image stays in the same place while the picture is enlarged. Now consider the point under the mouse cursor. Every pixel above and to the left of the cursor has become 20% larger. This displaces the point under the cursor by 20% downward and to the right. Meanwhile, the cursor is in the same position.

为了补偿光标下面的点的位移,我们移动图像,使得点返回光标下。点向下和向右移动;我们将图像向上和向左移动相同的距离。

To compensate for the displacement of the point under the cursor, we move the image so that the point gets back under the cursor. The point moved down and right; we move the image up and left by the same distance.

请注意,图像可能在缩放操作之前已在画布中移动,因此光标在水平位置在放大之前,图像为 currentMouseX - image.getLeft(),同样用于垂直位置。

Note that the image might have been moved in the canvas before the zooming operation, so the cursor's horizontal position in the image is currentMouseX - image.getLeft() before zooming, and likewise for the vertical position.

我们计算缩放后的位移:

This is how we calculate the displacement after zooming:

var dx = (currentMouseX - image.getLeft()) * (factor - 1),
    dy = (currentMouseY - image.getTop()) * (factor - 1);

最后,我们通过将光标移回光标下方来补偿位移:

Finally, we compensate for the displacement by moving the point back under the cursor:

image.setLeft(image.getLeft() - dx);
image.setTop(image.getTop() - dy);

我将此计算整合到您的演示中,并做了以下小提琴:

I integrated this calculation into your demo and made the following fiddle:

https://jsfiddle.net/sbpag9fr/3/

我也实现了缩小操作。

这篇关于图像变焦以鼠标位置为中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆