JSFiddle - React, Tailwind, and code Playground
by Rich Shih
HTML
<canvas id="myCanvas" width=500px height=400px>
Your browser does not support HTML5 Canvas.
</canvas>
Babel + JSX
let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
// The best way to create an animation loop is by using the brand-new window.requestAnimationFrame() method. This new method uses a delta timer to tell your JavaScript program exactly when the browser is ready to render a new frame of animation. The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. This method has not been implemented across all browsers, we are going to use window.setTimeout() for applications in this book.
function drawScreen() {
let fadeIn = true;
context.globalAlpha = 1;
context.fillStyle = "blueViolet";
context.fillRect(0, 0, 500, 500);
context.globalAlpha = 0.25;
if (fadeIn) {
alpha += 0.01;
if (alpha >= 1) {
alpha = 1;
fadeIn = false;
}
} else {
alpha -= 0.01;
if (alpha < 0) {
alpha = 0;
fadeIn = true;
}
}
context.globalAlpha = alpha;
}
function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen()
}