You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.0 KiB

/*
* 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
* Date: 2019-10-20
* Version: 1.2
*/
"use strict";
function zoom(factor, imgName) {
let winW = Math.max(document.documentElement.clientWidth, window.innerWidth);
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};
// 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 = 0, 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};
};
}