HomeWriters RSS

Coding Challenge #4

The Task

We have recently featured three different canvas tutorials, which show the basics of how to draw shapes on the canvas, and pushing further how to animate them.

There will be times when you want to draw a square with sides of length 'x' on the canvas, or a triangle with sides 'y', or even a pentagon with sides of length 'n'.

The task is to write a function in JavaScript that will take a single parameter - the number of sides - and then draw that shape on the canvas which has predefined context ctx, the center of this shape should lie at the centre of the canvas, and all sides must be 40px in length.

To get you started the function might look something like this:

function drawShape(n){
    var centre = [canvas.width/2, canvas.height/2];

If you need some help, take a look at how many angles there are in total within a polygon with sides n, assume all angles are the same.