Canvas Experiments 1-4

Here are my first experiments with canvas:

The canvas is a HTML element that I have not explored very much. I am very interested in the idea that you can create programmatic animation. I initially followed a Youtube tutorial (Lis, 2017) to create a bouncing ball. I then amended the JavaScript in various ways to create different effects.

The basics for the JavaScript are:

// set a variable 'canvas' and use document.querySelector to 'grab' the canvas element.
var canvas = document.querySelector('canvas'); 
// set the height and width to the viewport size
canvas.width = window.innerWidth;
canvas.width = window.innerHeight;

The way the canvas works with animation requires clearing the canvas between frames. “Probably the biggest limitation is, that once a shape gets drawn, it stays that way. If we need to move it we have to redraw it and everything that was drawn before it” (Mozilla Developer Network, 2017). To do this we use the ‘clearRect()’ method which “sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content” (ibid., 2017).

So, in basic terms: We draw a shape, clear the canvas, then redraw the shape(s) in a new position – repeating this cycle creates the animation.

To draw a shape we can create a function (see below for explanation):

function drawCircle() {
 c.arc(x, y, radius, 0, Math.PI*2, false);
 c.strokeStyle = "#FF3333";

The beginPath() method creates a starting point (if there was a previous shape it disconnects the last point of that shape with this first point of this shape) – it’s a bit like taking the pencil off the page to start a new shape.

We are drawing a full arc to create a circle, but we could draw any section of arc. The parameters are the arc method are as follows:

  • x = x co-ordinate
  • y = y co-ordinate
  • radius = radius of the arc
  • aStart = Starting angle of arc given in radians (0 is 90 deg or 3 o’clock position).
  • aEnd = End angle of arc given in radians (to get radians use Math.PI*0.5 per quarter circle e.g. Math.Pi*2 is full circle.)
  • anti-clockwise = Boolean to decide direction arc is drawn.

The strokeStyle property is used here to define a hex colour code. It does do more, see here (Mozilla Developer Network, 2017).
Then the final line, the stroke() actually draws the shape.


Please find all references here.

Leave a Reply