Last active
March 12, 2023 07:29
-
-
Save air/61d6a8510924664e8cde to your computer and use it in GitHub Desktop.
flip colours and images at 60fps
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
<html> | |
<!-- | |
- GIF is too slow | |
- flipping colours in JS is easy | |
- Using backgroundImage is flickery | |
- With preload: fixed! | |
--> | |
<head> | |
<style> | |
body { | |
background: radial-gradient(ellipse at center, #7d7e7d 0%, #0e0e0e 100%); | |
} | |
</style> | |
<script> | |
// start a preload to kill le flickering | |
var boss1 = new Image(); | |
var boss2 = new Image(); | |
boss1.src = 'boss1.png'; | |
boss2.src = 'boss2.png'; | |
var delayColour = 500; | |
var delayPng = 500; | |
var lastFrameTimeColour = 0; | |
var lastFrameTimePng = 0; | |
function animate() { | |
// coloured block | |
var timeSinceLast = performance.now() - lastFrameTimeColour; | |
if (timeSinceLast > delayColour) { | |
lastFrameTimeColour = performance.now(); | |
drawColours(); | |
} | |
// image block | |
timeSinceLast = performance.now() - lastFrameTimePng; | |
if (timeSinceLast > delayPng) { | |
lastFrameTimePng = performance.now(); | |
drawPng(); | |
} | |
requestAnimationFrame(animate); | |
} | |
// when preload is done, get animating | |
boss2.onload = function() { | |
requestAnimationFrame(animate); | |
}; | |
</script> | |
</head> | |
<body background> | |
Header text. | |
<div id="flipColour" style="width: 300px; height: 300px; margin-left: auto; margin-right: auto"> | |
</div> | |
<script> | |
var colourToggle = false; | |
var flipColour = document.getElementById("flipColour"); | |
flipColour.onmousedown = function() { | |
delayColour = (delayColour > 0 ? 0 : 500); | |
}; | |
function drawColours() { | |
if (colourToggle) { | |
flipColour.style.backgroundColor = "darkblue"; | |
} else { | |
flipColour.style.backgroundColor = "darkred"; | |
} | |
colourToggle = !colourToggle; | |
} | |
</script> | |
Middle text. | |
<div id="flipPng" style="width: 768px; height: 544px; background-size: 100% 100%; margin-left: auto; margin-right: auto"> | |
</div> | |
<script> | |
var pngToggle = false; | |
var flipPng = document.getElementById("flipPng"); | |
flipPng.onmousedown = function() { | |
delayPng = (delayPng > 0 ? 0 : 500); | |
}; | |
function drawPng() { | |
if (pngToggle) { | |
flipPng.style.backgroundImage = "url('boss1.png')"; | |
} else { | |
flipPng.style.backgroundImage = "url('boss2.png')" | |
} | |
pngToggle = !pngToggle; | |
} | |
</script> | |
Footer text. | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment