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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…