Drawing a circle on the canvas is pretty easy.

And using a for loop, drawing 200 circles on the canvas is still easy.

But what if we wanted to draw 200 circles and then move them around, what if we wanted them all to have a different colour, or size? What if we need to know where each circle is at any given frame?

When animating using the canvas, there comes a point in time when we need to use objects to organise and keep track of what we are drawing. Sure, we could use a library like Fabric/Easel/Paper.js but that is quite an overhead and may not be necessary for a simple canvas animation. Once we understand how to use Objects to control the canvas, we can understand what Canvas libraries are doing at their core, and let them handle the more tedious/complicated stuff.

Introducing the Circle Object

  function Circle(x,y,rad,color) {
    var _this = this;

    // constructor
    (function() {
        _this.x = x || null;
        _this.y = y || null;
        _this.radius = rad || null;
        _this.color = color || null;
    })();

    this.draw = function(ctx) {
        if(!_this.x || !_this.y || _this.radius || _this.color) {
            console.error('Circle requires an x, y, radius and color');
            return;
        }
        ctx.beginPath();
        ctx.arc(_this.x, _this.y, _this.radius, 0, 2 * Math.PI, false);
        ctx.fillStyle = _this.color;
        ctx.fill();
    }
}


In the Circle object I've added some properties, as well as a draw function.

Now we have an object to keep track of the circle properties, we can create a number of Circles, and draw each of them out in an animation loop. At any time we can check where each circle is or modify it's properties.

Properties don't have to be limited to position, color and size though, they could be any number of things such as vectors (force, velocity) or a relationship to another object.

Perhaps, one of the best things about using the Circle object and its properties, is we can now easily tween those properties to create non-linear movement.

So, give it a go! Your shapes/particles needn't be circles, they could be anything you can draw on the canvas. With Javascript objects, a bit of creativity and a little bit of math, there is an unlimited number of effects you can create on the canvas. I look forward to seeing your pens soon.

This is my first post on CodePen so if you enjoyed it or found it useful, please comment below! And make sure you comment with your cool canvas pens for mine and others' inspiration :)


26,227 14 134