The magnifying glass is not an effect that is difficult to achieve, but it is more cumbersome because it involves some precise numerical calculations. In the future, I will write articles about the JavaScript magnifying glass series from time to time, each time talking about one point, from point to point. and finally complete the entire effect.
This time we first learn how to move the lens on the thumbnail. (This is DEMO)
The DOM structure composed of the thumbnail and the lens is as follows .
I place the image in a thumbnail container And the lens node, using the thumbnail container as a relative position reference, modifies the position of the lens when the mousemove event is triggered. In other words, the problem we want to solve is to calculate the position of the upper left corner of the lens in the thumbnail container. Calculate the lens displacement The JavaScript code is as follows.
/**
* Get the position of the lens on the magnification target element
* @param ev triggered event
* @param thumb thumbnail object
* @param glass lens object
* @return x: The horizontal position of the lens on the magnification target element, y: the vertical position of the lens on the magnification target element
*/
function getGlassOffset(ev, thumb, glass) {
var offset = {
left:0,
top:0
};
// offset
var thumbOffset = getCumulativeOffset(thumb);
//The position of the mouse on the page
var mousePoint = getMousePoint(ev);
//The actual size of the lens
var glassSize = getSize(glass) ;
// Actual size of thumbnail
var thumbSize = getSize(thumb);
// Cursor horizontal position
var cursorX = mousePoint.x - thumbOffset.left;
/ / Lens lateral offset
offset.left = cursorX - glassSize.width / 2;
if(offset.left < 0) {
offset.left = 0;
} else if( offset.left > thumbSize.width - glassSize.width) {
offset.left = thumbSize.width - glassSize.width;
}
// Cursor vertical position
var cursorY = mousePoint.y - thumbOffset.top;
// Lens vertical offset
offset.top = cursorY - glassSize.height / 2;
if(offset.top < 0) {
offset .top = 0;
} else if(offset.top > thumbSize.height - glassSize.height) {
offset.top = thumbSize.height - glassSize.height;
}
return offset;
}
The position of the upper left corner of the lens in the thumbnail container = mouse position - the position of the upper left corner of the thumbnail - half the size of the lens
When the lens is outside the container, Move the lens to the side. Please take a peek at
DEMO for all the code. (Do you know why I wrote the last article to get the mouse position through JS?)
Leave a question for after-class thinking, when the lens has a border How to ensure that the frame does not affect the accuracy of lens movement?