Skip to content

Instantly share code, notes, and snippets.

@mvasilkov
Last active November 26, 2019 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvasilkov/ecfaced4ae8ad04e882fa464b187df50 to your computer and use it in GitHub Desktop.
Save mvasilkov/ecfaced4ae8ad04e882fa464b187df50 to your computer and use it in GitHub Desktop.
Вороны клюют твою задачу, Джузеппе!
<!doctype html>
<html lang="en">
<head>
<meta charset="utf8">
<title>Crows peck at your crops, Giuseppe!</title>
<style>
#thing {
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<div id="thing"></div>
<script>
/* Color utils */
function toRgb(colorString) {
if (colorString.length != 7) {
throw Error(`Expected '#RRGGBB', got '${colorString}'`)
}
const n = parseInt(colorString.slice(1), 16)
return [(n & 0xFF0000) >> 16, (n & 0xFF00) >> 8, n & 0xFF]
}
function toColor(rgbTuple) {
return `rgb(${rgbTuple})`
}
/* Linear interpolation utils */
function lerp(a, b, t) {
return a * (1 - t) + b * t
}
function lerpRgb(a, b, t) {
return a.map((_a, n) => Math.round(lerp(_a, b[n], t)))
}
/* This is the thing */
function changeColor(node, startColor, endColor, duration = 2019) {
startColor = toRgb(startColor)
endColor = toRgb(endColor)
let then = -1
function render(now) {
if (then == -1) {
then = now
}
const t = Math.min((now - then) / duration, 1)
if (t < 1) requestAnimationFrame(render)
else console.log('Done')
node.style.backgroundColor = toColor(lerpRgb(startColor, endColor, t))
}
requestAnimationFrame(render)
}
/* Crows peck at your crops, Giuseppe! */
const A = '#FF0080'
const B = '#B2D7FF'
changeColor(document.getElementById('thing'), A, B)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment