Last active
January 19, 2020 03:16
-
-
Save radio-alice/6695f6c1dc6ece33b51242b9b9cf0a03 to your computer and use it in GitHub Desktop.
script for making fun text shadows that respond to the mouse as if it were a light source
This file contains 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
// script for making fun text shadows that respond to the mouse as if it were a light source | |
// by Zach (zach@anemon.es) | |
// do whatever you want with this | |
// make sure the element's width and height are only as big as the text | |
// (e.g. width: max-content) | |
// include like <head>... <script src="/path/to/shadows.js"></script> </head> | |
// check out demo usage here => https://github.com/radio-alice/anemon.es/blob/fern/index.js#L3 | |
const getElementLocation = element => { | |
const { top, left, width, height } = element.getBoundingClientRect() | |
return { | |
x: left + width / 2, | |
y: top + height / 2 | |
} | |
} | |
const getMousePosition = e => ({ | |
x: e.clientX, | |
y: e.clientY | |
}) | |
const getDistanceToElement = (e, elementLocation) => { | |
const mousePosition = getMousePosition(e) | |
return { | |
x: mousePosition.x - elementLocation.x, | |
y: mousePosition.y - elementLocation.y | |
} | |
} | |
const adjustOffsets = distance => { | |
const magnitude = Math.sqrt(Math.pow(distance.x, 2) + Math.pow(distance.y, 2)) | |
return { | |
x: (1 - distance.x) / magnitude, | |
y: (1 - distance.y) / magnitude | |
} | |
} | |
// could convert to ES6 module here | |
const applyShadow = (event, element, color, scalar) => { | |
const elementLocation = getElementLocation(element) | |
const { x, y } = adjustOffsets(getDistanceToElement(event, elementLocation)) | |
element.style.textShadow = `${x * scalar}em ${y * scalar}em ${color}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment