Tag Archive: Html5

HTML5 Canvas Fountain

May 22, 2010

HTML5 Fountain Animation Screenshot

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).

View Demo.

Converting to Javascript was pretty straight forward, after all the syntax has the same origins. It’s slightly easier to achieve in Actionscript as Flash has built in the concepts of independent visual objects, wheras the canvas tag does not and so you need to roll your own, which for a simple example as this is not a problem, and I’m guessing there will be some nice JS frameworks around fairly soon which will make the job easier. Strongly tempted to convert a load of the other tutorials from Foundation AS3 to Javascript as well but not a great use of time and the author may (understandably) hunt me down and beat me to death.

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…

(download the js source)


Just the required bits…

  1. <canvas width="500" height="400" id="MyCanvas">I AM A CANVAS!</canvas>

That was easy. You just need a canvas tag. I’ve given it the original id of ‘MyCanvas’. Next up…

The Javascript

Once again, I’ve used jQuery to get things moving quickly, you don’t need to but it makes life easier.

  1. var tId;
  2. var cHeight = 0;
  3. var cWidth = 0;
  4. var numBalls = 100;
  5. var balls = new Array();

First we set some global variables as follows:

  • tId: A variable to hold the interval id. We don’t actually need this but it’s handy if we wanted to add more functionality later, and good practice (IMHO).
  • cHeight, cWidth: The canvas dimensions. Will be set shortly.
  • numBalls: The number of balls you wish to display. Change this if you fancy.
  • balls: An array of ball objects.
  1. function Ball(){
  2.         this.xPos = 0;
  3.         this.yPos = 0;
  4.         this.vx = 0;
  5.         this.vy = 0;
  6.         this.radius = 5;
  7.         this.colour;
  8.         this.wind;
  9.         this.gravity;
  10.         this.sizeWobble;
  12.         this.reset = function() {
  13.                 this.xPos = cWidth / 2;
  14.                 this.yPos = cHeight / 2;
  15.                 this.vx = Math.random() * 10 5;
  16.                 this.vy = Math.random() * 10 5;
  17.                 this.colour = randomColour();
  18.                 this.wind = Math.random() * 2 1;
  19.                 this.gravity = Math.random() * 2 1;
  20.                 this.radius = Math.random() * 20 + 5;
  21.                 this.sizeWobble = Math.random() * 2 1;
  22.         }
  23. }

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.

  1. jQuery(document).ready(function($){
  3.         // Set canvas values
  4.         cHeight = parseInt($(‘#MyCanvas’).height());
  5.         cWidth = parseInt($(‘#MyCanvas’).width());
  7.         // Generate balls
  8.         for(var i = 0;i < numBalls;i++){
  9.                 balls.push(new Ball());
  10.                 balls[i].reset();
  11.         }
  13.         tId = setInterval(‘drawBalls()’, 50);
  15. });

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.

  1. function drawBalls(){
  2.         clearCanvas();
  3.         var context = document.getElementById(‘MyCanvas’).getContext(‘2d’);
  4.         for(var i = 0;i < numBalls;i++){
  5.                 drawCircle(balls[i].xPos, balls[i].yPos, balls[i].radius, balls[i].colour);
  6.                 balls[i].vy += balls[i].gravity;
  7.                 balls[i].vx += balls[i].wind;
  8.                 balls[i].xPos += balls[i].vx;
  9.                 balls[i].yPos += balls[i].vy;
  10.                 if(balls[i].radius > 2){
  11.                         balls[i].radius += balls[i].sizeWobble;
  12.                 }
  14.                 if(
  15.                         balls[i].xPos balls[i].radius > cWidth||
  16.                         balls[i].xPos + balls[i].radius < 0||
  17.                         balls[i].yPos balls[i].radius > cHeight||
  18.                         balls[i].yPos + balls[i].radius < 0
  19.                         ){
  20.                                 balls[i].reset();
  21.                         }
  23.         }
  24. }

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:

  1. Draw it using drawCircle, passing it’s current position, radius and colour
  2. Adjust it’s x and v velocity modifiers using the gravity/wind values
  3. Update it’s stored position using it’s velocity modifiers
  4. If it’s radius is greater than 2 adjust it by it’s sizeWobble! (the min size check ensures it doesn’t completely disappear)
  5. If it is no longer on the canvas, reset it.

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…

  1. function clearCanvas(){
  2.         $(‘#MyCanvas’).attr(‘width’,$(‘#MyCanvas’).attr(‘width’));
  3. }
  5. function randomColour(){
  6.         var red = Math.round(Math.random() * 255);
  7.         var green = Math.round(Math.random() * 255);
  8.         var blue = Math.round(Math.random() * 255);
  9.         return "rgb(" + red + ", " + green + ", " + blue + ")";
  10. }
  12. function drawCircle(cx, cy, radius, colour){
  13.     var ctx = document.getElementById(‘MyCanvas’).getContext(‘2d’);
  14.     ctx.fillStyle = colour;
  15.     ctx.strokeStyle = "rgb(60, 80, 50)";
  16.     ctx.beginPath();
  17.     ctx.arc(cx,cy,radius,0,Math.PI*2,true); // Outer circle
  18.     ctx.fill();
  19.     ctx.stroke();
  20. }

View Demo.

HTML 5 Graph Slider

April 27, 2010

HTML5 Graph Slider_1272407446781

Been having a play with HTML5, very excited by the new semantics and especially keen on the new canvas tag. Aware that it’s not going to be supported everywhere in the immediate future but it’s a great step in the right direction. I don’t think it’s going to be the immediate flash killer some have made it out to be anytime soon (I love flash and AS and have no desire to see them go), but it can certainly work as a good alternative to flash for simple animation and interactivity. Once the decent JS frameworks add more functionality to support it it’s going to make life a lot more interesting.

I’ve put together a couple of experimental demos with HTML5 this week, this is the first. It’s a dynamic graph viewer. It can accept data via javascript and update the graphs on the fly. The data in question in the demo is supplied by the sliders but it can come from anywhere you like. I’ve kept the graphics basic for the sake of the demo.

View Demo.

I’ve not written any sort of tutorial/code article before, so bear with me, feel free to just download the source.

I’ve used jQuery and jQuery UI in the name of agile development. The jQuery ui for the sliders and a couple of jQuery statements to get measurements and deal with events, these could be easily swapped out for alternative frameworks or more verbose standard javascript.


View the source of the demo for the full HTML, I’ll just include the pertinent parts here:

  1. <div id="Graphs">
  2.         <canvas width="200" height="150" id="Graph1"></canvas>
  3.         <canvas width="200" height="150" id="Graph2"></canvas>
  4. </div>
  5. <div id="Controls">
  6.         <div id="Slider1"></div>
  7.         <div id="Slider2"></div>
  8.         <div id="Slider3"></div>
  9.         <div id="Slider4"></div>
  10. </div>

This sets up two canvases, one for each graph, I’ve named them the imaginative ‘Graph1’ and ‘Graph2’. The controls div contains four divs to be converted to jQuery UI sliders (one for each point / bar on the graphs).

The Javascript

First off we set up a couple of global variables:

  1. var graphPadding = 10;
  2. var colours = new Array("rgb(200,0,0)","rgb(0,200,0)","rgb(0,0,200)","rgb(0,200,200)");

graphPadding is just a number to use for spacing items of the graphs out. I’ve just set a single number to use for all margins, spacing, etc to keep things simple. colours is an array of colour codes, one for each of the graph points.

Next we initialise with the nice jQuery document.ready function:

  1. jQuery(document).ready(function($){
  3.         /* Generate Nice jQuery UI Sliders */
  4.         $(‘#Slider1, #Slider2, #Slider3, #Slider4’).slider({
  5.                 slide: function(event,ui){drawGraphs();}
  6.         });
  8.         /* Set some random initial values for the sliders */
  9.         $(‘#Slider1, #Slider2, #Slider3, #Slider4’).each(
  10.                 function(){
  11.                         $(this).slider(‘value’,Math.random() * 100);
  12.                 }
  13.         );
  15.         drawGraphs();
  17. });

The first command sets up the jQuery UI sliders including giving them the appropriate event handler to redraw the graph whenever any of them are changed. The second command just sets each slider to a random value. Next we call drawGraphs to draw their initial state.

Now we have the main graph drawing function, this is set up to draw both graphs in one go.

  1. function drawGraphs(){
  2.         /* Get the canvas dimensions, we know they are both the same so we shall be lazy and only check once */
  3.         var cHeight = parseInt($(‘#Graph1’).height());
  4.         var cWidth = parseInt($(‘#Graph1’).width());
  6.         /* Clear the Canvases */
  7.         clearCanvas($(‘#Graph1’));
  8.         clearCanvas($(‘#Graph2’));

First we get the canvas dimensions, these could be stored as constants/globals somewhere or hard coded but I like the flexibility of checking on the fly. Really we should check each one individually and split the graph drawing into two functions but it’s a demo and I don’t care. Then we clear each canvas to start drawing on it using a function which will be defined below.

  1. /* Graph 1  – The line graph */
  2.         // Get Context
  3.         var canvas = document.getElementById("Graph1");
  4.         var ctx = canvas.getContext("2d");
  6.         // Set Stroke Style
  7.         ctx.strokeStyle = "rgb(0,0,0)";

Prepare to draw the first graph by getting a reference to the appropriate canvas then calling getContext on it. Then we set the stroke style to black.

  1. // Draw Axis
  2.         ctx.beginPath();
  3.         ctx.moveTo(graphPadding, graphPadding);
  4.         ctx.lineTo(graphPadding,cHeight graphPadding);
  5.         ctx.lineTo(cWidth graphPadding, cHeight graphPadding);
  6.         ctx.stroke();
  7.         ctx.closePath();

Draw the axis, a simple case of drawing two straight lines. We use a combination of the canvas dimensions and the graphPadding global to work out the positions.

  1. // Display a point for each slider, spaced equally
  2.         var availableSpace = cWidth (graphPadding * 4);
  3.         var horizSpace = availableSpace / 3;
  4.         var vertSpace = cHeight (graphPadding * 4);

Work out how much space we actually have to draw the points in. The first point is two sets of graphPadding from the left and the last is two from the right hence the * 4. Same applies vertically.

  1. // Create an array of y points
  2.         var points = new Array();
  3.         for(var i = 0;i < 4;i++){
  4.                 // Get Ypos
  5.                 var yPercent  = ($(‘#Slider’ + (i + 1)).slider(‘value’) 100) * 1;
  6.                 var yPos = (vertSpace * (yPercent / 100) + (graphPadding * 2));
  7.                 points.push(yPos);
  8.         }

The points will be equally spaced horizontally so we just need to get their vertical position. Loop through the sliders, get the value for each one (0 – 100), work out the percentage of the available vertical space and add it to the points array.

  1. // Draw Lines
  2.         var xPos = graphPadding * 2;
  3.         ctx.beginPath();
  4.         for(i = 0;i < 4;i++){
  5.                 if(i == 0){
  6.                         ctx.moveTo(xPos, points[i]);
  7.                 }else{
  8.                         ctx.lineTo(xPos, points[i]);
  9.                 }
  10.                 xPos += horizSpace;
  11.         }
  12.         ctx.stroke();
  13.         ctx.closePath();

Draw the graph lines. We separate the line drawing and point drawing as when we draw a circle it calls closePath which knackers up our lines (there’s probably a better way). To draw the lines we loop through the points and draw a line between each one.

  1. // Draw Dots
  2.         var xPos = graphPadding * 2;
  3.         for(i = 0;i < 4;i++){
  4.                 drawCircle(ctx, xPos, points[i], 4, colours[i]);
  5.                 xPos += horizSpace;
  6.         }

To draw the points we just loop through the points array again, drawing a circle at each one, again the horizontal position of each point is fixed.

I’ll cut out most of the code for Graph 2 as it’s identical. The part of interest is:

  1. // Work out width of each bar
  2.         var availableWidth = cWidth (graphPadding * 6);
  3.         var barWidth = availableWidth / 4;
  4.         var maxHeight = cHeight (graphPadding * 3);
  6.         // Draw bars
  7.         var xPos = graphPadding * 2;
  8.         for(i = 0;i < 4;i++){
  9.                 // Work out height
  10.                 var h = maxHeight * ($(‘#Slider’ + (i + 1)).slider(‘value’) / 100);
  11.                 var yPos = cHeight h (graphPadding * 2);
  12.                 ctx.fillStyle = colours[i];
  13.                 ctx.fillRect(xPos, yPos, barWidth, h);
  15.                 xPos += barWidth + graphPadding;
  17.         }

Here we work out the available space for the bars by subtracting the appropriate number of graphPaddings from the total available space then dividing the result by the number of bars. We work out the max height of each bar by deleting 4 * graphPadding from the total available height.

Then we loop through the sliders, get the percentage value from each one and set it’s bar to the given percentage of the total height.

That’s pretty much it. I’ve used two additional helper functions which are based on those found at the Mozilla Canvas tutorial, they shouldn’t need any explanation:

  1. /**
  2.  * clearCanvas
  3.  * Clears a canvas, by setting it’s width.
  4.  */
  5. function clearCanvas(element){
  6.         $(element).attr(‘width’,$(element).attr(‘width’));
  7. }
  9. /**
  10.  * drawCircle
  11.  * Draws a circle
  12.  */
  13. function drawCircle(ctx, x, y, radius, colour){
  14.         ctx.fillStyle = colour;
  15.         ctx.beginPath();
  16.     ctx.arc(x, y, radius,0,Math.PI*2,true); // Outer circle
  17.     ctx.fill();
  19. }

So, there you go. Dynamic graphs without flash or server side graphics libraries. These could of course be achieved pretty much entirely with CSS and JS but it’s been a nice intro to HTML5 and the canvas tag.

I’ve not given this a huge amount of testing (or thought) as really for my own entertainment but hope it’s of interest.

Follow Me…

  • Follow me on Facebook
  • Follow me on Instagram
  • Follow me on Tumblr
  • Follow me on Flickr
  • Follow me on YouTube
  • Follow me on Pinterest
  • Follow me on Twitter

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts


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).

Buy My Stuff

Help fund my existence. Buy my stuff (t-shirts, art prints, stock images & graphics)

What Ho Guvnor! Spiffing robot t-shirts to hide your nipples.