May 22, 2010
A bit more arsing about with HTML5. Purely decorative, completely non-interactive this time. An animated fountain based on one I wrote in AS3 which in turn was based closely on one from the absolutely brilliant Foundation ActionScript 3 Animation: Making Things Move! (seriously, if you need a good basis in programmed animation/interaction this book is a godsend, explained in simple terms and with a brilliant separation of concept from code so the information and tutorials can be easily applied to languages other than Actionscript 3).
The app is pretty simple, it generates a load of circles, each with it’s own direction, velocity, colour and size which move away from the center, when they are off the screen they are reset with new velocity, colour, size, etc and put back to the center again. That’s it. Here’s the code, it’s not very polished but it works…
Just the required bits…
That was easy. You just need a canvas tag. I’ve given it the original id of ‘MyCanvas’. Next up…
Once again, I’ve used jQuery to get things moving quickly, you don’t need to but it makes life easier.
First we set some global variables as follows:
Define a ‘Ball’ class. The xPos/yPos determine the ball’s current position in the canvas. vx and vy are the Ball’s x and y velocity. Wind and Gravity and horizontal and vertical force. The strangely named ‘sizeWobble’ is the amount the ball radius changes each frame. The reset function sets up the ball, most parameters are randomly generated, xPos and yPos are set to the center of the canvas.
The core of the script. Wrapped up in a nice jQuery document ready handler. First we set the globals for the canvas dimensions (as used by the reset method in the Ball class). Then we loop as many times as we want balls, create a new ball each loop instance, add it to the balls array and reset it.
Once our balls are created we use setInterval to call the ‘drawBalls’ function every 50 microseconds.
This is the function that’s called each ‘frame’ by the setInterval command. First we clear the canvas. Next we get a context for the canvas. Then we loop through the array of balls. For each one we:
That’s pretty much it, the remaining three functions are helpers. clearCanvas clears the canvas by setting it’s width (must find a more logical method of doing this). randomColour returns a random colour in the appropriate format and drawCircle draws a circle to the canvas…
I am Bob. This is my blog. It is an outlet and a substitute for real life. It contains my art, photography, illustration and thoughts on mental health (I deal with anxiety on a pretty much constant basis).
Help fund my existence. Buy my stuff (t-shirts, art prints, stock images & graphics)