Canvas Animation Basics
For me, one of the most fascinating improvements to the web as been the advancements with in-browser animations and gaming. In this article, we'll create a quick animation to display how the new canvas element works.
To get things started, we must add the new HTML5 canvas element with a couple properties to set the id
, width
, and height
:
<canvas id="canvas" width="100" height="100" />
Initializing Our Code
With the canvas element added, we can start the JavaScript by creating a reference to the canvas element and the canvas context, which will be 2D for this article.
// Store Reference To The Canvas & Set Context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
Creating A Draw Function
Next, we need to create the draw function that will recursively call itself to draw each frame of our animation.
// Draw on our canvas.
function draw() {
// Clear Canvas At The Start Of Every Frame
ctx.clearRect(0,0,100,100);
// Begin Line Path & Set Starting Point
ctx.beginPath();
ctx.moveTo(Math.random() * 70, Math.random() * 70);
// Draw Additional Randomly Placed Lines
for (var i = 0; i < 25; i++) {
ctx.lineTo(Math.random() * 70, Math.random() * 70);
}
// Enable Stroke & Set Stroke Color
ctx.strokeStyle = "#333";
ctx.stroke();
// Call Draw Function Again To Continue
// Drawing To Canvas To Create Animation
window.requestAnimationFrame(draw);
}
In this function we're making several calls to the 2D context reference to clear the canvas and draw a series of random lines. For more information on these methods, check out the wonderful CanvasRenderingContext2D Documentation on MDN.
This could be handled with a setInterval()
or setTimeout()
function. But, instead I've opted to use the new requestAnimationFrame()
function that will handle our animations much more efficiently and wont continue to run in the background when our tab isn't in focus.
Initializing The Draw Function
As the final step, we need to call the draw function to initialize the loop and start our animation.
// Initialize The Draw Function
draw();
Live Demo
See the Pen Basic Canvas Animation Example by Travis Maynard (@travm) on CodePen.
I hope this quick introduction to the new canvas element has been helpful. This is barely scratching the surface, so If you enjoyed this, I encourage you to take a look at some additional documentation on MDN to explore more in-depth explanations of what I've introduced here.