Created
June 7, 2017 01:58
-
-
Save joetannenbaum/022678ee486e1ad72fd88b6da3f20455 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
spotlitt.faces.forEach(face => { | |
const el = document.getElementById(face.el_id) | |
// Make sure we're between 0 and 100 | |
const inRange = (val) => { | |
return Math.min(Math.max(val, 0), 100) | |
} | |
const getXPos = (width, height) => { | |
const imageWidth = (face.width * height) / width | |
let xDiff = (width / 2 / imageWidth) * 100 | |
const { x } = face | |
if (x > 50) { | |
xDiff *= -1 | |
} | |
return inRange(x - xDiff) | |
} | |
const getYPos = (width, height) => { | |
const imageHeight = (face.height * width) / height | |
let yDiff = (height / 2 / imageHeight) * 100 | |
const { y } = face | |
if (y > 50) { | |
yDiff *= -1 | |
} | |
// Center of face doesn't really include hair, bump it down just a bit to make it look right | |
const buffer = 5 | |
return inRange(y - buffer - yDiff) | |
} | |
const positionFace = () => { | |
// Grab the current width/height of the element | |
const { width, height } = el.getBoundingClientRect() | |
// Position the background with the new coordinates | |
el.style.backgroundPositionX = getXPos(width, height) + '%' | |
el.style.backgroundPositionY = getYPos(width, height) + '%' | |
} | |
// Listen for the window resizing | |
window.addEventListener('resize', positionFace, 100) | |
// Position face on initialization | |
positionFace() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment