Implementation Time

We'll cover the following...

In the previous section, you learned at a high-level what goes into drawing and animating something on your canvas. You basically have two main steps:

  1. Draw
  2. Clear

In this section, we’ll create a simple circle slide animation and see how these draw and clear steps map to lines of sweet JavaScript code.

Adding Your Canvas

The first thing we are going to do is add the canvas element that will house our beautiful animation. You’ve seen this a bunch of times already, and you probably already have a page setup. If you don’t have a page already setup, create a blank HTML page and add the following HTML and CSS into it:

Press + to interact
<!DOCTYPE html>
<html>
<head>
<title>Simple Canvas Example</title>
<style>
canvas {
border: 10px #333 solid;
}
</style>
</head>
<body>
<div id="container">
<canvas id="myCanvas" height="450" width="450"></canvas>
</div>
<script>
</script>
</body>
</html>

If you preview this in your browser, you will see an empty square outlined in a dark gray color.

Drawing Our Circle

The next step is to draw the circle we would like to animate. Inside your script tag, add the following lines:

Press + to interact
var mainCanvas = document.querySelector("#myCanvas");
var mainContext = mainCanvas.getContext("2d");
var canvasWidth = mainCanvas.width;
var canvasHeight = mainCanvas.height;
function drawCircle() {
}
drawCircle();

There is nothing exciting going on here. We are just writing some boilerplate code to more easily access the canvas element and its drawing context. While this is pretty boring, the exciting stuff is about to happen…

Inside this drawCircle function, add the following code that will actually draw our circle:

  • HTML
  • JavaScript
javascript

So far, almost everything we’ve done has been a review of all the canvas-related things we’ve been learning together. I mention almost because there is something new that I want to call out. That is the clearRect ...