Adding HTML5 ‘Canvas’ element to Wordpress


Posted in: html5, wordpress | Save to del.icio.us | 6 Apr 2010



Only if partially, but HTML 5 is slowly getting increased support from various browsers. Some of the HTML 5 features like ‘canvas’ and ‘video’ are supported by browsers like Firefox, Safari, Google Chrome and Opera. In this post we will look into how to add the HTML 5 ‘canvas’ tag to your wordpress posts.

The Canvas element consists of a drawable region defined in HTML on which you can dynamically draw graphics and animations using Javascript. The canvas API provides a nice set of drawing functions to play with.

Before we proceed you can see what the final output will look like at the end of this post. Note that your browser must support the ‘canvas’ tag to display the animation.

Detecting Canvas support

Before we add any HTML 5 elements to our page, we need to check if that element is supported by the browser. Even though most latest browsers support the ‘Canvas’ tag, browser like IE and other old browsers do not support the it. We can use some standard detection techniques, like the following to check if the ‘canvas’ element is supported:

if(!!document.createElement('canvas').getContext) {
// Canvas tag is supported, so do something here
}

Although the above will do, here we will use the ‘Modernizr’ library to accomplish the detection job. With the library, checking for HTML5 support is quite easy. Modernizr is a small and JavaScript library that helps in feature detection to test the current browser against upcoming CSS3 and HTML 5 elements. The below code will check for the ‘canvas’ support:

if (Modernizr.canvas) {
// Canvas tag is supported, so do something here
}

Here is another Modernizr example to test for audio support:

if (Modernizr.audio && Modernizr.audio.ogg){
    /* 
        Check for HTML 5 audio support and see if the 
        browser additionally supports the ogg codec.
    */
}

Adding the ‘canvas’ tag to your wordpress posts

To display canvas elements in your posts all you have to do is add the following tag to any of your posts. The code in our ‘loader.js’ file will then insert the appropriate canvas element in the div. The ‘title’ attribute references a javascript script that will be dynamically loaded to draw on the ‘canvas’ element. So in the following example, the file ‘bounce.js’ will be loaded dynamically. ‘bounce.js’ is a script that displays bouncing balls on the ‘canvas’ element. But it can be anything – a script to draw graphs, pictures, gradients etc.

<div id="html5" title="bounce"></div>

Now that we have added the appropriate tag to the post, we need to load and run the appropriate Javascript files to display our Canvas graphic. Here is where the ‘loader.js’ file comes into picture.

Getting help from loader.js

The ‘loader.js’ file acts as a bootstrap; inserting the ‘canvas’ element into the appropriate div tag and loading and executing the javasacript to draw into the Canvas. The ‘loader.js’ file contains the following code:

 
jQuery(document).ready(function($) {
 
/* Check to see if 'canvas' is supported
   in the current browser */
if (Modernizr.canvas) {
 
    /* Check if the 'html5' id is defined */
    var canvas = $('#html5');
    if(canvas.length) {
        /* If yes, then insert the 'canvas' element in the div */
        canvas.html('<canvas id="canvas"></canvas>');
 
        /* Get the name of the javascript file to load.
           This is specified in the 'title' tag of the div
           in the post.
        */
        var fileToLoad = canvas.attr('title');
 
        /* Set appropriate width and height for the canvas */
        $('#canvas').attr('width', '520');
        $('#canvas').attr('height', '220');
 
        /* Load external javascript that we want to run */
        $.getScript("PATH-TO-YOUR-JAVASCRIPT/" + fileToLoad  + ".js", 
                    function(){
                        start();
                    });
    }
}
});

This is how the loader.js bascially works. It first checks to see if ‘canvas’ is supported in the browser. If yes then it checks for the ‘html5′ id on the page, and if found inserts the canvas tag into the div. This id can be anything you like, as long as it is a valid id. Next it sets the div width and height and gets the ‘title’ attribute of the div. We have used the ‘title’ attribute to store the javascript file name that we want to load dynamically. In the above example that file would be ‘bounce.js’. Next we load the javascript file with jQueries ‘getScript’ function. The ‘getScript’ function takes a callback function which will be run once the ‘bounce.js’ file has been loaded. Here the callback function is ’start()’ , which is defined in the ‘bounce.js’ file.

Adding the javascript files to your Wordpress theme

At this point we have 2 JavaScript files at our disposal; one to detect canvas support and the other the loader. We need to add those 2 files to our Worpdress themes ‘functions.php file, as shown below:

 
/* 
Add the following lines at the top to your 
‘functions.php’ in your theme directory.
 
'_X_' being your theme name.
 
*/
 
wp_enqueue_script('modernizr', 
                  '/wp-content/themes/_X_/javascript/modernizr-1.1.js', 
                  false,
                  '1.1');
 
wp_enqueue_script('myloader', 
                  '/wp-content/themes/_X_/javascript/loader.js', 
                  array('modernizr', 'jquery'),
                  '1.0');

The first line loads the ‘modernizr-1.1.js’ file, while the second loads our ‘loader.js’ file. As the ‘loader.js’ files depends on the jQuery and the Modernizr library, the second line also ensures that both libraries ( jQuery & Modernizr ) are loaded before the ‘loader.js’ script.

The canvas drawing Javascript

The Javascript file that handles all the animation and drawing routines is stored in the ‘bounce.js’ file. Although the animation is not something to write about home, it shows the basic concept of how to implement a ‘canvas’ tag in a wordpress post.

The final output

Browsers that support the ‘canvas’ tag should see a few bouncing balls below.

Adding additional Canvas tags

You can add additional Canvas tags to your others post, but with a different id, handling the processing in the ‘loader.js’ file as shown for the above example.






5 Responses

1

Jani Hartikainen

April 9th, 2010 at 5:47 pm

Wouldn’t it be simpler to just include the canvas tag in the markup straight away?

If the browser doesn’t support canvas, it will display the text you put inside the tag, so you can just do something like Your browser does not support canvas, which would somewhat simplify the JS code.

sameer

April 9th, 2010 at 9:49 pm

Of course that would have been simple, but I wanted to control the ‘canvas’ tag itself and the text inside from Javascript. You can now maybe add a Flash equivalent graphics if the canvas tag is not available, all from the JS script, without going and changing the markup in the posts. You can maybe also add a SVG graphics in its place.

Actually my original purpose was to add other HTML5 elements like video and other new elements from javascript, so I deferred adding the markup directly in the post.

3

Jani Hartikainen

April 13th, 2010 at 11:20 am

True, replacing it with some kind of alternative content like that could be a good reason to do it via scripting as you’ve shown here.

4

Noisy, Annoying, and Flashing HTML5 Advertisements | Tucker Watson

May 9th, 2010 at 12:24 pm

[...] it was fairly easy and intuitive to create – the hardest part was integrating it into a Wordpress Post! It works in Chrome (minus the audio), looks slightly different in Firefox, and doesn’t work [...]

5

alex

June 12th, 2010 at 12:11 pm

hi, nice script!

I modified it a bit to read the width and height from the div attributes

var fileToLoad = canvas.attr(‘title’);
var c_height = canvas.attr(‘height’);
var c_width = canvas.attr(‘width’);
var canvasId = ‘#canvas_’+fileToLoad;
canvas.html(”);
/* Set appropriate width and height for the canvas */
$(canvasId).attr(‘width’, c_width);
$(canvasId).attr(‘height’, c_height);

/* Load external javascript that we want to run */
$.getScript(“PATH-TO-YOUR-JAVASCRIPT/” + fileToLoad + “.js”,
function(){
start();
});

Leave a Reply

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

  • Users Online

    • 14 Users Online
    • 13 Guests, 1 Bot
  • RECENT COMMENTS

    ON TWITTER