HTML5 Canvas Animation

Anton Lytvynov
2 min readApr 28, 2021

--

How to add dynamic effects to your canvas elements?

We ll build this animation

Html

<html lang="en">
<head>
<title>Canvas Animation</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet">
</head>

<body>
<canvas id="c" width="800" height="600">
This is a message for old browsers
</canvas>

<script src="script.js"></script>
</body>
</html>

Style

#c {
border: 1px solid;
display: block;
width: 800px;
height: 600px;
margin: 0 auto;
}

JavaScript

window.onload = function () {
let canvas = document.getElementById("c");
let context = canvas.getContext("2d");

let start = new Date();

window.requestAnimationFrame(drawRandomColoredRectangle);

function drawRandomColoredRectangle() {
let now = new Date();
if (now - start >= 1000) {
start = now;

// Clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);

// Random Colors
let color = createRandomRGBColor();
let fillOpacity = Math.random();
let fillColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + fillOpacity + ')';
let borderColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ')';

let x = getRandomInt(0, canvas.width);
let y = getRandomInt(0, canvas.height);
let w = getRandomInt(0, canvas.width - x);
let h = getRandomInt(0, canvas.height - y);

// Draw Rectangle
context.beginPath();
context.fillStyle = fillColor;
context.strokeStyle = borderColor;
context.rect(x, y, w, h);
context.stroke();
context.fill();
}

// Animate
window.requestAnimationFrame(drawRandomColoredRectangle);
}

function createRandomRGBColor() {
let red = getRandomInt(0, 257);
let green = getRandomInt(0, 257);
let blue = getRandomInt(0, 257);
return {r: red, g: green, b: blue};
}

function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}


window.requestAnimationFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
};

Result

You can check the code for this part here.

Thank you for your attention.

LinkedIn, Twitter, https://lytvynov-anton.com

--

--

Anton Lytvynov

CEO & Founder of Lytvynov Production, Senior web developer, architect, cryptocurrencies trader, https://lytvynov-production.com