Instantly share code, notes, and snippets.

@air /flip.html
Last active Apr 4, 2017

Embed
What would you like to do?
flip colours and images at 60fps
<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