I am using a modified version of this w3schools tutorial for a magnifying glass W3Schools. I’m trying to make my glass as functional as possible, dealing with it being able to render even on the furthest edges of my image.
Unfortunately I’m having an issue with the top and left edges “freezing” the glass whenever the edge of the glass reaches the edge of the image. This is most likely due to the glass rendering the image from the top left corner, creating the problem of trying to render part of an image that doesn’t actually exist.
My question is how can I get my glass to render the zoomed image all the way up to the edges of the image, while still keeping the glass centered over my cursor. I want the overflow to smoothly be able to hide outside of the image, without constraining the glass at all within the image itself.
I attached the full code here: FullFiddle and a testable example here: TestFiddle (may have to press run again to get the glass to update properly). Notice how the top and left edges don’t magnify properly all the way to the edge while the bottom and right edges do. Let me know if theres any other questions.
// The moveMagnifier function sets the position of the glass to the position of the cursor
function moveMagnifier(e) {
e.preventDefault();
pos = getCursorPos(e); // Calls function to get cursor position
x = pos.x;
y = pos.y;
glass.style.left = `${x - w}px`; // Centers glass position over cursor
glass.style.top = `${y - h}px`;
glass.style.backgroundPosition = `-${x * zoom - w}px -${y * zoom - h}px`;
}
// Function for finding the cursor based on the bounds of the image
function getCursorPos(e) {
let xPos = e.clientX - imgRect.left; // Gets cursor position based on image position
let yPos = e.clientY - imgRect.top;
return { x: xPos, y: yPos };
}
TLDR: Magnifying glass is extending out of bounds and want it to be able to handle zooming in on the edges of the image.
P.S: If anyone has a better way to handle hiding the actual overflow of the glass or any other corrections please let me know.
I would assume a solution would be to create an invisible padding of sorts around each image that still allows it to render properly. I don’t know how I would go about that properly though.