Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Last active April 28, 2020 03:04
Show Gist options
  • Select an option

  • Save sandrabosk/b58a9ac2e08ef8a1506cd75d33ac7636 to your computer and use it in GitHub Desktop.

Select an option

Save sandrabosk/b58a9ac2e08ef8a1506cd75d33ac7636 to your computer and use it in GitHub Desktop.
canvas animations - requestAnimationFrame
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Canvas Animations</title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<!-- add js file in the end when the DOM is already loaded -->
<script src="index.js"></script>
</body>
</html>
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const cWidth = canvas.width;
const cHeight = canvas.height;
let speed1 = 1;
let speed2 = 2;
let speed3 = 3;
// uncomment the following three lines to see how three rectangles are going to be created, but no dynamic for now
// to see how these become dynamic, comment the following three lines out and then see what is going on
// in the updateCanvas() function below
// ctx.fillRect(50, 10, 50, 50);
// ctx.fillRect(150, 10, 50, 50);
// ctx.fillRect(250, 10, 50, 50);
function clearCanvas() {
ctx.clearRect(0, 0, cWidth, cHeight);
}
function drawCanvas(x, y, w, h, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
}
// the previous two functions () and drawCanvas() are included inside updateCanvas() below:
function updateCanvas() {
// in order to see animation, something needs to change
// in our case that is going to be speed1,2 and 3 which
// we will use as "y" since our rectangles are going to start falling from up to down, vertically
speed1 += 1;
speed2 += 2;
speed3 += 3;
// clear the canvas
clearCanvas();
// redraw the canvas
// drawCanvas(x, y, width, height, "color");
drawCanvas(50, speed1, 50, 50, 'red');
drawCanvas(150, speed2, 50, 50, 'green');
drawCanvas(250, speed3, 50, 50, 'yellow');
// 1st way to make some animation is using setTimeout()
// this way is the same as the recursive function
// the benefit is to be able to influence the speed through the milliseconds (in example below it's 30ms ==> the function updateCanvas() gets called every 30ms)
// setTimeout(() => updateCanvas(), 30);
// 2nd way: requestAnimationFrame(someFunctionNameWithoutParentheses)
// very often used but requires a bit of manual work to influence the speed
requestAnimationFrame(updateCanvas);
// 3rd way: setInterval(() => updateCanvas(), framesPerSecond)
// setInterval(() => updateCanvas(), 10000 / 60);
}
// un-comment out updateCanvas() below to see how it works,
// but make sure you comment out again to see how the next example works
updateCanvas();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment