Quantcast
Viewing all articles
Browse latest Browse all 25

Drawing Animated Sun Rays in HTML Canvas

I wanted to recreate the classic kids' book sun ray effect - but have it animating and drawing in HTML canvas. You can see it in action below or on my server's default page.

Change colour: blue/light blue, black/white, yellow/gold.

Okay, so for starters you need to initialize the canvas object. I'm going to assume because you're here, you know how to do that, so I'm going to skip over explaining that portion of the code.

So, to do this, we're going to need to get the co-ordinates of certain points from the outside of a circle. There are probably other, more efficient ways to do it, but this to me seems like the easiest way.

Image may be NSFW.
Clik here to view.

The canvas bounds are marked in yellow. The co-ordinates we need to draw are marked on the diagram - once we have those, we can then draw each ray with the following code:

context.moveTo(mX, mY);
context.lineTo(c1X, c1Y);
context.lineTo(c2X, x2Y);
context.lineTo(mX, mY);
context.fill();

Admittedly it's easier said than done - to get the c1 and c2 pair we need to use some of JavaScript's trigonometry functions, which admittedly I find very difficult to get my head around.

So, after a bit of searching, I found a post on a forum asking how to get the co-ordinates of the two points given the mid point, the length of the ray and the angle. Perfect! This is exactly what we need here. So, this is the function that will help us with that written in JavaScript based on that forum post:

So you feed it the midpoint co-ordinates, length and angle (in radians), and it returns an object with X and Y co-ordinates.

Now all we need to do is iterate a loop that can supply that function with radians, and put everything together.

And if you want to animate them as I have, all you need to do is call the above code on a timer, and increment an "offset" value. The offset value is then added to the "angle" value as it is calculated, resulting in rays at a slightly different rotation.

Below is the full code from this project in object form - to use it, include it in your page and call it like this:

rays.init('canvasID', 'colour1', 'colour2');

You can see it in action on my server's default page.


Viewing all articles
Browse latest Browse all 25

Trending Articles