Friday, August 26, 2011

Balls to the Canvas!

To play around a bit with the canvas element, I decided to write this:



You can increase or decrease the number of balls on screen using the UP and DOWN arrows respectively.

View it in action


The source is here: https://github.com/dreasgrech/balls

Some implementation details

The background

To implement the colorful background, I'm using a cylindrical-coordinate representation of the RGB color model, known as HSV (Hue Saturation Value). Keeping the saturation and value to a constant 100 (max), I'm iterating through values 0-360 for the hue thus achieving the blending of colors. When the hue reaches 360, I reset it back to 0 and the cycle starts over.

The initial value of the hue is randomly chosen at the beginning.

Balls

All of the balls' attributes are randomly generated i.e. the initial position, size, color, speed and angle.

Since collision detection is only applied once the balls hit the edges of the browser window and the edges are axes aligned, I'm simply inverting the part of the velocity's depending to which edge is hit.

If the ball hits either the left or right edge, the x is inverted and if the ball hits the top or bottom edge, the y is inverted.

Resizing the window

I'm hooking to window.onresize so that once the browser window is resized, I adjust the width of the canvas appropriately and also remove the balls that are now out of screen.