JavaScript magnifiers are the first component I wrote after becoming a front-end. I learned a lot from them. it has been more than half a year now. I hope to organize and rethink some of the solutions while I still have an impression on myself and improve them, writing these ideas into a magnifier is not a difficult result, but it is complicated because it involves some precise numerical calculations. in the future, I will occasionally write articles about the JavaScript magnifier series. Each time I talk about a dot, a dot and a plane, the final effect will be completed.
This time, we will first learn how to move the lens on the thumbnail. (This is a DEMO)
The DOM structure composed of thumbnails and lenses is as follows.
The Code is as follows:
I placed images and lens nodes in the thumbnail container, and used the thumbnail container as a reference for the relative position. When the mousemove event is triggered, I modified the lens position. in other words, the problem we need to solve is to calculate the position of the lens in the upper left corner of the thumbnail container. the JavaScript code for calculating lens displacement is as follows.
The Code is as follows:
/**
* Obtain the position of the lens on the enlarged target element.
* @ Param ev: events triggered
* @ Param thumb thumbnail object
* @ Param glass: Lens object
* @ Return x: the horizontal position of the lens on the target element. y: the vertical position of the lens on the target element.
*/
Function getGlassOffset (ev, thumb, glass ){
Var offset = {
Left: 0,
Top: 0
};
// Offset
Var thumbOffset = getCumulativeOffset (thumb );
// Place the cursor over the page
Var mousePoint = getMousePoint (ev );
// Actual lens size
Var glassSize = getSize (glass );
// Scale down the actual size of the image
Var thumbSize = getSize (thumb );
// Horizontal cursor position
Var cursorX = mousePoint. x-thumbOffset. left;
// Lens horizontal 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;
}
// Vertical position of the cursor
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;
}
Position in the upper left corner of the lens in the thumbnail Container = mouse position-position in the upper left corner of the thumbnail-half of the lens size
When the lens is out of the container, pull the lens by the side. For all the code, see the DEMO. (Do you know why I used JS to get the mouse position in the previous article ?)
Leave a question after class. When the lens has a border, how can we ensure that the border does not affect the accuracy of the lens movement?