Skip to content

Instantly share code, notes, and snippets.

@SteveOscar
Created April 1, 2016 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SteveOscar/8f7e6daca5120e2884d52762c773cb03 to your computer and use it in GitHub Desktop.
Save SteveOscar/8f7e6daca5120e2884d52762c773cb03 to your computer and use it in GitHub Desktop.
Creating Basic HTML Canvas Animations

Creating Basic Animations With HTML Canvas

Using the HTML <canvas> element, it's possible to create custom animations and interactive games that run in the browser. It's a powerful tool, but also is literally a blank canvas that requires each frame of animation to be rendered by the code. Each frame is drawn, then the canvas is cleared, and the next frame is drawn, much like in traditional hand-drawn animation. This post will discuss how to create a very basic animation.

Canvas Setup

For this example we'll throw all of our code into one file. Create a new HTML document. In the <style> tags some CSS for basic styling of the canvas border (while we don't modify the contents of the canvas itself with CSS, we can style the display of the canvas element):

canvas {
    border: 3px #CCC solid;
}

And now in the body, add the actual canvas element, which has height and width attributes for setting the size of the canvas:

<div id="container">
    <canvas id="myCanvas" height="450" width="450"></canvas>
</div>
<div id="north_america_map" style="width: 600px; height: 400px"></div>

If you open this file in your browser, you should see a blank canvas.

Drawing on the Canvas

We've used HTML and CSS to setup and style the blank canvas, but drawing on and animating the canvas will accomplished with JavaScript. Let's place some the basic setup code in between the <script> tags. This will include grabbing the canvas and pointing to it with the canvas variable, and establishing the context (we will be drawing in two dimensions):

var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");

var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

function drawBall() {

}
drawBall();

We've also setup and called an empty drawBall function that will draw to the canvas. The way drawing is achieved is by calling functions on the context variable we set. Place the following code inside of the drawBall function, which will act as the first frame of the animation:

// clear the canvas at the beginning of the frame
context.clearRect(0, 0, canvasWidth, canvasHeight);

// then color in the background of the canvas
context.fillStyle = "red";
context.fillRect(0, 0, canvasWidth, canvasHeight);

// then draw the circle using canvas methods
context.beginPath();
var radius = 100;
context.arc(225, 225, radius, 0, Math.PI * 2, false);
context.closePath();

// color in the circle
context.fillStyle = "blue";
context.fill();

The clearRect function takes 4 arguments - beginning x point, beginning y point, width, and height. The beginPath function initiates the drawing of a shape, arc draws the shape, and closePath ends the drawing. At this point, in your browser you should see a red canvas with a blue ball in the middle. We have our first frame, now we just need to create more frames in which the ball is in a different position. Add the following code right below where you set the canvasWidth and canvasHeight variables:

var requestAnimationFrame = window.requestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            window.webkitRequestAnimationFrame ||
                            window.msRequestAnimationFrame;

While we won't go into the depths of requestAnimationFrame, it basically establishes what one frame is, and now the key for animation is we loop this in our main drawBall function. Add this line to the end of the drawBall function and notice that it takes the drawBall function as an argument. Recursion!

 requestAnimationFrame(drawCircle);

So now we simply need to change SOME aspect of the ball's position or size on each frame. For this example, we will just set the x-position to a random number, making the ball vibrate. At the beginning of the drawBall function, let's create a random x coordinate. Each time the animation frame runs, the ball will be at a slightly different position:

var xPoint = Math.floor(Math.random() * (200 - 180 + 1)) + 180

And now in the context.arc, set the first argument to our random point:

context.arc(xPoint, 225, radius, 0, Math.PI * 2, false);

You should now see the horrendously colored vibrating ball in your browser, congratulations! Incase you missed a step, here's the full code you should have in your file:

<!DOCTYPE html>
<html>
<head>
<title>Simple Canvas Example</title>
<style>
canvas {
    border: 3px #CCC solid;
}
</style>
</head>

<body>
<div id="container">
    <canvas id="myCanvas" height="450" width="450"></canvas>
</div>
<script>
var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");

var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

var requestAnimationFrame = window.requestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            window.webkitRequestAnimationFrame ||
                            window.msRequestAnimationFrame;

function drawBall() {
  var xPoint = Math.floor(Math.random() * (200 - 190 + 1)) + 190
  // clear the canvas at the beginning of the frame
  context.clearRect(0, 0, canvasWidth, canvasHeight);

  // then color in the background of the canvas
  context.fillStyle = "red";
  context.fillRect(0, 0, canvasWidth, canvasHeight);

  // then draw the circle using canvas methods
  context.beginPath();
  var radius = 100;
  context.arc(xPoint, 225, radius, 0, Math.PI * 2, false);
  context.closePath();

  // color in the circle
  context.fillStyle = "blue";
  context.fill();

  requestAnimationFrame(drawBall);
}
drawBall();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment