TagCanvas - HTML5 Canvas Tag Cloud

Skip to: download linksoptions listweighted tags pagemulti-colour and multi-font support.

TagCanvas is a Javascript class which will draw and animate a HTML5 canvas based tag cloud. I'm releasing it as open source under the LGPL v3 license. Below is an example.

Since the canvas is part of the HTML page, you can position things above or below it.

Cloud shape:

TagCanvas in Internet Explorer

The canvas element is not supported by Internet Explorer versions up to and including version 8. However, the tag cloud above should be working in IE thanks to the ExplorerCanvas (Google code site) Javascript include file that translates canvas functions into IE's VML. It is a bit slow, but it does work. Mostly.

At the time of writing you must use the latest trunk version of ExplorerCanvas, as the current version in the project downloads area does not have the required text output support.

Note again: the fading of image tags with distance does not work with the current version of Explorer Canvas. I've created a modified version of excanvas.js to make it work, which you can get from here. If you don't use image tags, or don't want images to fade with distance, then you should use the latest version from the Google code site linked above.

Internet Explorer 9 does support the canvas element, so excanvas.js is not required. The conditional comment required to include excanvas.js for earlier versions should look like this:

<!--[if lt IE 9]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
<script src="tagcanvas.min.js" type="text/javascript"></script>

Images

TagCanvas 1.3 was the first version to support image links - the first image found inside a link will be used instead of any text. Click the "Use image links" button below the example tag cloud above to see it in action.

Cloud shape

TagCanvas 1.11 adds an option for changing the shape of the cloud from the default sphere to either a horizontal or vertical cylinder. These look best with more tags, but I have added buttons to the example at the top of the page to show them working. The cylinders in this example are using the new lock option to keep them rotating about their axes.

Accelerometer / motion sensor

If you're using a laptop with a new-ish browser, take a look at the accelerometer page to see what happens when I find out hardware I didn't know I had is accessible from a browser.

Tag weighting

Starting in version 1.6 TagCanvas supports weighting of tags. Take a look at the TagCanvas with weighted tags page for more details and an example.

More examples

This is another canvas

And another canvas

Two more examples side-by-side. Clicking a tag in the first will reload the second with different content.

Icon 01 Icon 02 Icon 03 Icon 04 Icon 05 Icon 06 Icon 07 Icon 08 Icon 09 Icon 10 Icon 11 Icon 12 Icon 13 Icon 14 Icon 15 Icon 16 Icon 17 Icon 18 Icon 19 Icon 20

Complete example - stand-alone version

Here is the code for a full example page, using the stand-alone version of TagCanvas. It demonstrates passing in options and how to specify the list of tags to use.

<!DOCTYPE html>
<html>
  <head>
    <title>TagCanvas example</title>
    <!--[if lt IE 9]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
    <script src="tagcanvas.js" type="text/javascript"></script>
    <script type="text/javascript">
      window.onload = function() {
        try {
          TagCanvas.Start('myCanvas','tags',{
            textColour: '#ff0000',
            outlineColour: '#ff00ff',
            reverse: true,
            depth: 0.8,
            maxSpeed: 0.05
          });
        } catch(e) {
          // something went wrong, hide the canvas container
          document.getElementById('myCanvasContainer').style.display = 'none';
        }
      };
    </script>
  </head>
  <body>
    <h1>TagCanvas example page</h1>
    <div id="myCanvasContainer">
      <canvas width="300" height="300" id="myCanvas">
        <p>Anything in here will be replaced on browsers that support the canvas element</p>
      </canvas>
    </div>
    <div id="tags">
      <ul>
        <li><a href="http://www.google.com" target="_blank">Google</a></li>
        <li><a href="/fish">Fish</a></li>
        <li><a href="/chips">Chips</a></li>
        <li><a href="/salt">Salt</a></li>
        <li><a href="/vinegar">Vinegar</a></li>
      </ul>
    </div>
  </body>
</html>

Complete example - jQuery plugin version

This is a similar example page, this time using the jQuery plugin version of TagCanvas.

<!DOCTYPE html>
<html>
  <head>
    <title>TagCanvas jQuery example</title>
    <!--[if lt IE 9]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
    <script src="jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="jquery.tagcanvas.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        if(!$('#myCanvas').tagcanvas({
          textColour: '#ff0000',
          outlineColour: '#ff00ff',
          reverse: true,
          depth: 0.8,
          maxSpeed: 0.05
        },'tags')) {
          // something went wrong, hide the canvas container
          $('#myCanvasContainer').hide();
        }
      });
    </script>
  </head>
  <body>
    <h1>TagCanvas jQuery example page</h1>
    <div id="myCanvasContainer">
      <canvas width="300" height="300" id="myCanvas">
        <p>Anything in here will be replaced on browsers that support the canvas element</p>
      </canvas>
    </div>
    <div id="tags">
      <ul>
        <li><a href="http://www.google.com" target="_blank">Google</a></li>
        <li><a href="/fish">Fish</a></li>
        <li><a href="/chips">Chips</a></li>
        <li><a href="/salt">Salt</a></li>
        <li><a href="/vinegar">Vinegar</a></li>
      </ul>
    </div>
  </body>
</html>

1. Download the javascript file from here: tagcanvas.js version 1.12 / [Minified],
or the jQuery plugin version here: jquery.tagcanvas.js version 1.12 / [Minified]

The minified versions of the files have been compressed using the Yahoo! YUI Compressor.

My modified version of Explorer Canvas is here: excanvas.zip and the original is here.

2. Include the file into your page:

<!--[if lt IE 9]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
<script src="tagcanvas.js" type="text/javascript"></script>

or for the jQuery plugin:

 <!--[if lt IE 9]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
 <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
 <script src="jquery.tagcanvas.min.js" type="text/javascript"></script>

3. Add a canvas to your page, with the required width and height:

 <canvas width="300" height="300" id="myCanvas">
  <p>Anything in here will be replaced on browsers that support the canvas element</p>
 </canvas>

4a. If you don't care about supporting Internet Explorer versions up to 8, put your tag links inside the canvas. They will be shown as-is on browsers that do not support the canvas element:

 <canvas width="300" height="300" id="myCanvas">
  <p>Anything in here will be replaced on browsers that support the canvas element</p>
  <ul>
   <li><a href="http://www.google.com" target="_blank">Google</a></li>
   <li><a href="/fish">Fish</a></li>
   <li><a href="/chips">Chips</a></li>
   <li><a href="/salt">Salt</a></li>
   <li><a href="/vinegar">Vinegar</a></li>
  </ul>
 </canvas>

You don't have to use ul and li, any link inside the canvas will be found. The tag links may be outside the canvas and referenced by the id of a containing element - see below for details.

4b. If you DO want to support IE versions below 9, the tag links MUST BE OUTSIDE the canvas element or they can not be found by the TagCanvas script:

 <canvas width="300" height="300" id="myCanvas">
  <p>In Internet Explorer versions up to 8, things inside the canvas are inaccessible!</p>
 </canvas>
 
 <div id="tags">
  <ul>
   <li><a href="http://www.google.com" target="_blank">Google</a></li>
   <li><a href="/fish">Fish</a></li>
   <li><a href="/chips">Chips</a></li>
   <li><a href="/salt">Salt</a></li>
   <li><a href="/vinegar">Vinegar</a></li>
  </ul>
 </div>

— and this means you must pass the ID of the container your tags are in to TagCanvas (in this example the 'tags' div) as described below.

5. Initialise the TagCanvas class with the id of the canvas element when the page is loaded:

 <script type="text/javascript">
  window.onload = function() {
    try {
      TagCanvas.Start('myCanvas');
    } catch(e) {
      // something went wrong, hide the canvas container
      document.getElementById('myCanvasContainer').style.display = 'none';
    }
  };
 </script>

If your tag links are not inside the canvas, pass the id of the element containing the tags as an extra argument to the Start function:

      ...
      TagCanvas.Start('myCanvas','tagList');
      ...

To start TagCanvas using the jQuery plugin:

 <script type="text/javascript">
 $(document).ready(function() {
   if( ! $('#myCanvas').tagcanvas({
     textColour : '#ffffff',
     outlineThickness : 1,
     maxSpeed : 0.03,
     depth : 0.75
   })) {
     // TagCanvas failed to load
     $('#myCanvasContainer').hide();
   }
   // your other jQuery stuff here...
 });
 </script>

The tagcanvas() jQuery function also takes an optional argument for the id of the tag list container, which goes after the configuration options:

   ...
   $('#myCanvas').tagcanvas({
     depth : 0.75
   },'tagList');
   ...

The function returns true if the tag cloud is started successfully, false otherwise. This is so that you can handle the problem and replace the canvas with something else, or whatever you want to do.

Note that in the example above, the canvas container element is hidden when TagCanvas fails - the canvas itself may not respond to jQuery functions when running in a browser without canvas support.

6. That's it. The canvas itself is a part of the page, so you can style it with CSS - e.g. to add a border, margins, background, etc. TagCanvas does not draw a background onto the canvas, so the page background colour or image will show through.

The individual tags are drawn on the canvas using drawing functions, so they cannot be styled using CSS. Several options are supplied for specifying how they should be drawn, listed below.

Some options

There are a few options for modifying the way the cloud looks. Default values are shown in the second column below:

OptionDefaultDescription
interval[1]20 Interval between animation frames, in milliseconds
maxSpeed0.05 Maximum speed of rotation
minSpeed0.0 Minimum speed of rotation when mouse leaves canvas
decel0.95 Deceleration rate when mouse leaves canvas
minBrightness0.1 Brightness of tags at farthest point (0.0-1.0)
textColour[2]"#ff99ff" Colour of the tag text - empty string or null to use the colour of the original link.
textHeight15 Height of the tag text font (in pixels)
textFont[2]"Helvetica, Arial,
sans-serif"
Font family for the tag text - empty string or null to use the font of the original link.
outlineColour"#ffff99" Colour of the active tag highlight
outlineMethod"outline" Type of highlight to use. Options are outline for an outline at the same depth as the active tag, classic for the old-style outline on top of all tags, block for a solid block around the active tag and colour to change the colour of the text or image of the current tag to the outlineColour value.
outlineThickness2 Thickness of outline in pixels
outlineOffset5 Distance of outline from text, in pixels. This also increases the size of the active area around the tag.
pulsateTo1.0 Pulsate outline to this opacity (0.0-1.0)
pulsateTime3 Pulse rate, in seconds per beat
depth0.5 Controls the perspective (0.0-1.0)
initialnull Initial rotation, with horizontal and vertical as an array, e.g. [0.8,-0.3]. Values are multiplied by maxSpeed.
freezeActivefalse Set to true to pause movement when a tag is highlighted.
frontSelectfalse Set to true to prevent selection of tags at back of cloud.
txtOpttrue Text optimisation, converts text tags to images for better performance.
txtScale2 Scaling factor of text when converting to image in txtOpt mode.
reversefalse Set to true to reverse direction of movement relative to mouse position.
hideTagsfalse Set to true to automatically hide the tag list element if TagCanvas is started successfully.
zoom1.0 Adjusts the relative size of the tag cloud in the canvas. Larger values will zoom into the cloud, smaller values will zoom out.
wheelZoomtrue Enables zooming the cloud in and out using the mouse wheel or scroll gesture.
zoomStep0.05 The amount that the zoom is changed by with each movement of the mouse wheel.
zoomMax3.0 Maximum zoom value.
zoomMin0.3 Minimum zoom value.
shadow"#000000" Colour of the shadow behind each tag.
shadowBlur0 Amount of tag shadow blurring, in pixels.
shadowOffset[0,0] X and Y offset of the tag shadow, in pixels.
weight[3]false Set to true to turn on weighting of tags.
weightMode[3]"size" Method to use for displaying tag weights. Should be one of size, colour or both.
weightSize[3]1.0 Multiplier for adjusting the size of tags when using a weight mode of size or both.
weightGradient[3]{0:'#f00', 0.33:'#ff0',
0.66:'#0f0', 1:'#00f'}
The colour gradient used for colouring tags when using a weight mode of colour or both.
weightFrom[3]null The link attribute to take the tag weight from. The default of null means that the weight is taken from the calculated link font size.
shape"sphere" The shape of the cloud. Currently supported are sphere, hcylinder for a cylinder that starts off horizontal and vcylinder for a cylinder that starts off vertical.
locknull A value of "x" limits rotation of the cloud to the (horizontal) x-axis, and a value of "y" limits rotation to the (vertical) y-axis. (These are strings, so the quotes are required)

To use these options for the stand-alone version, set the corresponding class variables before calling Start:

 <script type="text/javascript">
 window.onload = function() {
  TagCanvas.textColour = '#ffffff';
  TagCanvas.outlineColour = '#ff9999';
  TagCanvas.Start('myCanvas');
 };
 </script>

Alternatively, from version 1.5 you may pass in as a third argument to the Start function an object with the required options as attributes:

 <script type="text/javascript">
 var options = {
  textColour: '#fff',
  textHeight: 20,
  depth: 0.99
 };
 window.onload = function() {
  // use internal link list, so second argument is ''
  TagCanvas.Start('myCanvas', '', options);
 };
 </script>

for the jQuery plugin, pass the relevant parameters into the tagcanvas function:

 <script type="text/javascript">
 $(document).ready(function() {
   $('#myCanvas').tagcanvas({
     textColour : '#ffffff',
     outlineColour : '#ff9999'
   });
 });
 </script>

Projects using TagCanvas

Some developers have managed to do more with TagCanvas, so I'm happy to link to their work here. If you know of any other projects that use TagCanvas, please let me know and I'll add them to the list.

What's new?

Version 1.12
Added multi-font and multi-colour support. Added outlineMethod option for different ways to highlight the active tag. Now also uses fewer resources when cloud is stationary.
Version 1.11.1
Fixed bug in jQuery plugin version where cloud would not animate in IE if interval option was not set.
Version 1.11
Added zooming using mouse wheel, horizontal and vertical lock options, cylinder shapes.
Version 1.10
Better handling of mouse movement. Improved txtOpt mode quality with txtScale option.
Version 1.9
Improved image tag compatibility with IE 6-8. Various small optimisations.
Version 1.8
Added speed improvements with txtOpt option. Added frontSelect option.
Version 1.7.1
Fixed a .srcElement is undefined error that was appearing in Firefox.
Version 1.7
Added weightFrom and interval options, improved IE support, and a load of internal changes to improve efficiency.
Version 1.6.1
Fixed hideTags in jQuery version. Some minor optimizations.
Version 1.6
Added weighting of tags, a zoom option and tag shadow options. Also improved calculation of tag text sizes.
Version 1.5
Adds support for running multiple clouds on one page. Also fixes a bug where clicking a link with a target would open it twice.
Version 1.4.2
Improves compatibility with IE9.
Version 1.4.1
Bugfix - right-clicks (and middle-clicks) were triggering links before, but now only left-clicks will.
Version 1.4
Now supports click event handlers on the links so TagCanvas will work better with other Javascript and jQuery scripts. There's also a new option, minSpeed for keeping the cloud moving when the mouse leaves the canvas.
Version 1.3
Adds some support for using explorer canvas, using image link tags and selection of the tag list by id. Since the source of the links can now be specified, this is also the first version to support being restarted.
Version 1.2
Adds several new options: reverse, freezeActive, initial, pulsateTo and pulsateTime. The jQuery plugin version is also slightly smaller than the previous version.
Version 1.1.1
Improves compatibility with older jQuery versions, and also copes better with FireFox 3.0.x. The older FireFox version supports the canvas element, but not in the same way as the newer version. For now the stand-alone version will emulate IE behaviour in FireFox 3.0.x by moving the contents of the canvas into a div and deleting the canvas. The jQuery version will return false and let you deal with the fallout.
Version 1.1
Adds support for adjusting the perspective depth effect, the outline thickness and distance, and also uses a new algorithm to space the tags around the cloud better. This is also the first version available as a jQuery plugin as well as the stand-alone version.

Help!

As usual, this code doesn't come with any guarantees. But if you get stuck, find any bugs or have suggestions for improvements, please contact me at the usual address, graham(at)goat1000.com.