/* * zoom.js * function for the purpose of my portfolio to zoom into * images inside their box without touching the rest of the layout. * Author: phga/teord * Date: 2019-10-20 * Version: 1.1 */ function zoom(factor, imgName) { let img = document.getElementById(imgName); let magni = img.parentElement; magni.style.backgroundImage = `url("${img.src}")`; let offset = {x: img.width * factor, y: img.height * factor}; // Fix for firefox, somehow width larger than content (inline-block) magni.style.width = "100%"; magni.style.width = img.width; // setup the padding (bigger zoom canvas) magni.style.padding = offset.y + "px " + offset.x + "px"; // adjust the margin to ged rid of the extra size gained from padding magni.style.margin = -offset.y + "px " + -offset.x + "px"; // Added a mouse(enter|move|leave) to make img transparent and show bg-img when it should be visible img.addEventListener("mouseenter", (e) => { img.style.opacity = 0; }); img.addEventListener("mousemove", (e) => { moveBackground(getOffsetToMiddle(e)); }); img.addEventListener("mouseleave", (e) => { img.style.opacity = 1; }); // Function to move the bg-img according to the current position in img let moveBackground = function(pos) { // It is always good to draw stuff the brain can't process :E // * 2 because we have the offset on both sides // -pos because we have inverted controls magni.style.backgroundPosition = -pos.x * factor * 2 + "px " + -pos.y * factor * 2 + "px"; }; let getOffsetToMiddle = function(cursor) { let elem, x = y = 0; cursor = cursor || window.event; // get elem bounding box elem = img.getBoundingClientRect(); // calculate distance to middle of elem x = cursor.pageX - (elem.left + elem.width / 2); y = cursor.pageY - (elem.top + elem.height / 2); // We do not have a scrolling page but you never know x = x - window.pageXOffset; y = y - window.pageYOffset; return {x: x, y: y}; }; }