Getting started

10 Mar 2019 Code on Github


In this first lesson we'll create the basic organism object and display it on the canvas element.

This isn't going to be a full canvas tutorial, but I'll cover everything you need to know for this simulation. Mozilla has a nice tutorial if you want to learn more. I'll be using object-oriented programming - Khan Academy has a good tutorial on OOP.

All the code for this tutorial can be found on Github here. The code for this lesson is here.

Our first organism

Our organism is called a bloop, a name I took from the Daniel Shiffman tutorial. We'll represent it as a circle, so it will have a position (x- and y-coordinates), and radius.

var Bloop = function(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;

This is the object class, a template for building creatures. We can use it to create an instance of the Bloop object - our first creature.

This creature is called bloop1. It lives at position (100, 50) and has a radius of 8.

var bloop1 = new Bloop(100, 50, 8);

Creating our canvas

Our creature exists, but it's not much fun if we can't see it.

First off, we need to make a canvas element. This element needs to be in an HTML document. You can see any example here.

It needs an id so we can select it easily, and width and height attributes. You can make it as big as you like. I added a border to my canvas, so you can see it.

<canvas id="world" width="200" height="200">

Drawing our creature

Now, in the javascript file (or a different one to keep the drawing code separate from the creature code), we can create a function to draw the bloop.

First we need to get the canvas element, and then get its context, which allows use to access the canvas API.

var canvas = document.getElementById('world');
var ctx = canvas.getContext('2d');

Next we create a function that takes a bloop object and draws a circle, centered at (bloop.x, bloop.y), with radius bloop.r. The canvas API doesn't have a circle function, so we have to draw an arc, which starts at 0 radians and goes round for a full two pi radians. To save recalculating two pi, we can save it as a variable, TAU.

var TAU = Math.PI * 2;

function drawBloop(bloop) {
    ctx.fillStyle = 'rgb(40, 170, 10)';
    ctx.arc(bloop.x, bloop.y, bloop.r, 0, TAU, true);


Finally, pass the bloop1 creature to the draw function.


And that's it, we've drawn a circle on the screen: our creature exists, and we can see it. In the next lesson, we'll bring it alive by letting it move.