Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

javascript - Image zoom centered on mouse position

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.

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

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

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.

Result: Works fine for the first point, but after moving to another point and zooming, the image position is incorrect.

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});

What is going wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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.

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/fgLmyxw4/

I also implemented the zoom-out operation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...