Rendering Animations with Moving Objects on Canvas

Moving objects on HTML5 Canvas is really easy. I should have written on this topic before writing on gravity but it’s never too late! Let’s get started with the basics.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Canvas Coordinate System

I’ll keep things precise and short. You must already know about the Cartesian Coordinate Plane from your Math classes. It has 2 axis – X and Y. Both the axis are perpendicular to each other where the intersecting point (0,0) is in the center. Positive X goes to the right, negative X goes to left. Positive Y goes upwards, negative Y goes downwards.

Canvas coordinate system is almost similar with few differences. It has the origin point (0, 0) at top-left. Moving to the right increases the value on the x axis, while moving downward increases the value on the y axis. So, y axis is reversed.

Pretty straightforward and something you probably already know if you have ever worked with trivial functions on the canvas 2D context like lineTo.

Moving an Object

Changing the position of an object is as easy as changing it’s x and y positions on the coordinate system. Let’s say we have a rectangle drawn:

var x = 10,
	y = 10,
	w = 50,
	h = 50;

ctx.fillRect(x, y, w, h);

So we have a rectangle of dimensions 50×50 drawn at (10,10). How do we animate its position ?

var canvas = document.querySelector('canvas'),
	ctx = canvas.getContext('2d');

var W = canvas.width;
var H = canvas.height;

var x = 10,
	y = 10,
	w = 50,
	h = 50;

var vx = 2;
var vy = 2;

function draw() {
	ctx.clearRect(0, 0, W, H);
	
	x += vx;
	y += vy;
	ctx.fillRect(x, y, w, h);
}

setInterval(draw, 1000/60);

It’s the same piece of code, just that we’ve added all the extra code of setting the 2D context, canvas height, width, etc. in variables. We moved our fillRect to a new function called draw and we’re calling this new function via setInterval every 1000/60 milliseconds. Why this weird expression ? Because we want to render our animations at 60 Frames per second. 1000/30 would mean 30 FPS. This doesn’t necessarily mean that the browser is going to obey this. It all boils down to how busy CPU is, how much memory is available, etc.

The key part of this code is this:

x += vx;
y += vy;

vx is speed along the X axis while vy is speed in the Y direction. Speed with a direction is known as Velocity. We initially set both to 2 and then inside our draw function add our velocity to our X and Y values that we pass to fillRect. Hence, on every iteration, our rectangle is drawn onto a new position. Now this happens so fast (about 60 times a second) that we perceive it to be in motion.


(Refresh the demo if you do not see a square object in motion)

Feel free to tweak the velocities according to your desire. You can always negate the velocities to change the direction of the moving object!

Conclusion

This tutorial is meant to be really basic. I won’t take it any further but do check out this experiment by me. It’s pretty basic too! We generate particles with it’s initial position at the center of the canvas and then change it’s x/y positions with a randomly generated velocity. Quite fascinating how cool stuff this basic concept can build.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *

*