Skip to content

Instantly share code, notes, and snippets.

@smpnjn
Created September 26, 2021 11:31
Show Gist options
  • Save smpnjn/9ae4e5f06010cf10fa6c1669b24bac8d to your computer and use it in GitHub Desktop.
Save smpnjn/9ae4e5f06010cf10fa6c1669b24bac8d to your computer and use it in GitHub Desktop.
let calculateAngle = function(e, item, parent) {
let dropShadowColor = `rgba(0, 0, 0, 0.3)`
// If the button has a data-filter-color attribute, then use this for the shadow's color
if(parent.getAttribute('data-filter-color') !== null) {
dropShadowColor = parent.getAttribute('data-filter-color');
}
// If the button has a data-custom-perspective attribute, then use this as the perspective.
if(parent.getAttribute('data-custom-perspective') !== null) {
parent.style.perspective = `${parent.getAttribute('data-custom-perspective')}`
}
// Get the x position of the users mouse, relative to the button itself
let x = Math.abs(item.getBoundingClientRect().x - e.clientX);
// Get the y position relative to the button
let y = Math.abs(item.getBoundingClientRect().y - e.clientY);
// Calculate half the width and height
let halfWidth = item.getBoundingClientRect().width / 2;
let halfHeight = item.getBoundingClientRect().height / 2;
// Use this to create an angle. I have divided by 6 and 4 respectively so the effect looks good.
// Changing these numbers will change the depth of the effect.
let calcAngleX = (x - halfWidth) / 6;
let calcAngleY = (y - halfHeight) / 4;
// Set the items transform CSS property
item.style.transform = `rotateY(${calcAngleX}deg) rotateX(${calcAngleY}deg) scale(1.15)`;
// And set its container's perspective.
parent.style.perspective = `${halfWidth * 2}px`
item.style.perspective = `${halfWidth * 3}px`
// Reapply this to the shadow, with different dividers
let calcShadowX = (x - halfWidth) / 3;
let calcShadowY = (y - halfHeight) / 3;
// Add a filter shadow - this is more performant to animate than a regular box shadow.
item.style.filter = `drop-shadow(${-calcShadowX}px ${calcShadowY}px 15px ${dropShadowColor})`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment