-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimg-lens.js
More file actions
86 lines (68 loc) · 2.84 KB
/
img-lens.js
File metadata and controls
86 lines (68 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
;(function(lensW, lensH){
let currImage = null;
// Use the height the same as the width if not provided
if(!lensH){
lensH = lensW;
}
// Create lens element
const lens = document.createElement('div');
lens.style.width = `${lensW}px`;
lens.style.height = `${lensH}px`;
lens.style.backgroundRepeat = 'no-repeat';
lens.classList.add('lens');
document.body.appendChild(lens);
// Check if a given point is within an element bounding rectangle
const pointWithin = (elem, x, y) => {
const bcr = elem.getBoundingClientRect();
return x >= bcr.left && x <= bcr.right && y >= bcr.top && y <= bcr.bottom;
}
// Update currently viewed image and apply it to the lens background image
const updateImage = e => {
currImage = e.target;
lens.style.backgroundImage = `url(${currImage.src}`;
}
// Show the lens
const showLens = () => {
lens.classList.add('show');
}
// Hide the lens
const hideLens = () => {
lens.classList.remove('show');
}
// Handling mouse movement
const moveLens = (e) => {
// Get the cursor position relative to the viewport
const curX = e.x;
const curY = e.y;
// Adjust the center of the lens to the cursor position
lens.style.left = `${curX - lensW / 2}px`;
lens.style.top = `${curY - lensH / 2}px`;
if(currImage !== null){
const isCursorWithin = pointWithin(currImage, curX, curY);
// Hide the lens when it exceeds the current image boundaries
if(lens.classList.contains('show') && !isCursorWithin){
hideLens();
// Exit here, No need to perform unnecessary calculations
return;
}else if(!lens.classList.contains('show') && isCursorWithin){
showLens();
}
// Calculating width and height zoom factors between the displayed image size and the actual image size
const wzf = currImage.naturalWidth / currImage.width;
const hzf = currImage.naturalHeight / currImage.height;
// Calculate background position according to actual image size
const bcr = currImage.getBoundingClientRect();
const posX = Math.round((curX - bcr.left) * wzf - lensW / 2);
const posY = Math.round((curY - bcr.top) * hzf - lensH / 2);
lens.style.backgroundPosition = `${-posX}px ${-posY}px`;
}
}
// Find images with use-lens attribute
const images = document.querySelectorAll('img[use-lens]');
images.forEach(img => {
img.addEventListener('mouseenter', updateImage);
});
// Add mouseover event listener on found images
document.addEventListener('mousemove', moveLens);
lens.addEventListener('mousemove', moveLens);
})(150, 150);