Drawing stars with HTML5 Canvas

Update: I’ve since written a slightly different version that can draw n-sided polygons.

I was searching around for some decent HTML5 demos earlier and I noticed that there weren’t any particularly good tutorials or functions for drawing regular stars. Obviously Canvas is fine for drawing polygons and so I was able to produce this very simple function that uses the rotate() function to position the points:

function star(ctx, x, y, r, p, m)
    ctx.translate(x, y);
    for (var i = 0; i < p; i++)
        ctx.rotate(Math.PI / p);
        ctx.lineTo(0, 0 - (r*m));
        ctx.rotate(Math.PI / p);
        ctx.lineTo(0, 0 - r);

You call the function by using star(canvas, x of center, y of center, radius, number of points, fraction of radius for inset). Here are some examples. To create a five point star, therefore, you call star(ctx, 100, 100, 90, 5, 0.5). Here is an example of what that looks like:

Obviously because the function doesn’t actually set styles or shadows but this isn’t too difficult to implement. Here is a live demo of the star being drawn.


3 thoughts on “Drawing stars with HTML5 Canvas

  1. Thank you for posting this! I was searching for how to draw a regular 5-point star w/ canvas and javascript. All I could find were some crazy looking mis-shaped stars. I have been drawing a Scrabble board using canvas & javascript and needed a star for the middle. Made some modifications to the function to make it work and it’s perfect. Thanks again!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s