Book Image

HTML5 Canvas Cookbook

By : Eric Rowell
Book Image

HTML5 Canvas Cookbook

By: Eric Rowell

Overview of this book

The HTML5 canvas is revolutionizing graphics and visualizations on the Web. Powered by JavaScript, the HTML5 Canvas API enables web developers to create visualizations and animations right in the browser without Flash. Although the HTML5 Canvas is quickly becoming the standard for online graphics and interactivity, many developers fail to exercise all of the features that this powerful technology has to offer.The HTML5 Canvas Cookbook begins by covering the basics of the HTML5 Canvas API and then progresses by providing advanced techniques for handling features not directly supported by the API such as animation and canvas interactivity. It winds up by providing detailed templates for a few of the most common HTML5 canvas applications—data visualization, game development, and 3D modeling. It will acquaint you with interesting topics such as fractals, animation, physics, color models, and matrix mathematics. By the end of this book, you will have a solid understanding of the HTML5 Canvas API and a toolbox of techniques for creating any type of HTML5 Canvas application, limited only by the extent of your imagination.
Table of Contents (19 chapters)
HTML5 Canvas Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Canvas Security
Index

Canvas fallback content


As all the browsers do not support canvas, it's a good idea to provide fallback content so that the users know that something isn't working correctly in the event that their browser of choice does not support canvas. The simplest and most straightforward technique for handling browsers that don't support canvas is to add fallback content inside of the canvas tag. Typically, this content will be text or an image that tells the user that their outdated browser doesn't support canvas, followed by a suggestion for downloading a browser developed in this decade. Users who are using a browser that does support canvas will not see the inner content:

<canvas id="myCanvas" width="578" height="250">
            Yikes!  Your browser doesn't support canvas.  Try using 
Google Chrome or Firefox instead.
</canvas>

Canvas fallback content isn't always the best solution. For example, if the browser doesn't support canvas, you might want to alert an error message, redirect the user to a different URL, or even use a Flash version of the application as a fallback. The easiest way to detect whether the browser supports canvas is to create a dummy canvas element and then check whether we can execute the getContext method:

function isCanvasSupported(){
            return !!document.createElement('canvas').getContext;
        }

When the page loads, we can call the isCanvasSupported() function to determine whether or not the browser supports canvas and then appropriately handle the result.

This function uses one of my favorite JavaScript tricks, the double-not trick (!!), which determines whether or not the getContext method successfully executes. The first not of the double-not coerces the data type into a Boolean. As the act of coercing the data type yields the opposite result that we want, we can add a second not (!!) to flip the result back. The double-not trick is a super convenient way of checking whether or not a piece of code successfully executes, and in my opinion is much more elegant than wrapping a line of code with a try/catch block.

Detecting available WebGL contexts

If your canvas application leverages WebGL, you might also want to know which contexts the browser supports so that you can successfully initialize a WebGL application.

At the time of writing, there are five major contexts:

  • 2D

  • webgl

  • experimentl-webgl

  • moz-webgl

  • webkit-3d

All of the major browsers including Google Chrome, Firefox, Safari, Opera, and IE9 support the 2D context. However, when it comes to WebGL support, it's a completely different story. At the time of writing, Google Chrome and Safari support the experimental-webgl and the webkit-3d contexts, Firefox supports the experimental-webgl and the moz-webgl contexts, and IE9 does not support any form of WebGL.

To see this for yourself, you can create a function called getCanvasSupport() which loops through all of the possible contexts and uses the double-not trick to determine which contexts are available:

function getCanvasSupport(){
    // initialize return object
    var returnObj = {
        canvas: false,
        webgl: false,
        context_2d: false,
        context_webgl: false,
        context_experimental_webgl: false,
        context_moz_webgl: false,
        context_webkit_3d: false
    };
    // check if canvas is supported
    if (!!document.createElement('canvas').getContext) {
        returnObj.canvas = true;
    }
    
    // check if WebGL rendering context is supported
    if (window.WebGLRenderingContext) {
        returnObj.webgl = true;
    }
    
    // check specific contexts
    var contextMapping = {
        context_2d: "2d",
        context_webgl: "webgl",
        context_experimental_webgl: "experimental-webgl",
        context_moz_webgl: "moz-webgl",
        context_webkit_3d: "webkit-3d"
    };
    
    for (var key in contextMapping) {
        try {
            if (!!document.createElement('canvas').getContext(contextMapping[key])) {
                returnObj[key] = true;
            }
        } 
        catch (e) {
        }
    }
    
    return returnObj;
}

function showSupport(obj){
    var str = "";
    
    str += "-- General Support --<br>";
    str += "canvas: " + (obj.canvas ? "YES" : "NO") + "<br>";
    str += "webgl: " + (obj.webgl ? "YES" : "NO") + "<br>";
    
    str += "<br>-- Successfully Initialized Contexts --<br>";
    str += "2d: " + (obj.context_2d ? "YES" : "NO") + "<br>";
    str += "webgl: " + (obj.context_webgl ? "YES" : "NO") + "<br>";
    str += "experimental-webgl: " + (obj.context_experimental_webgl ? "YES" : "NO") + "<br>";
    str += "moz-webgl: " + (obj.context_moz_webgl ? "YES" : "NO") + "<br>";
    str += "webkit-3d: " + (obj.context_webkit_3d ? "YES" : "NO") + "<br>";
    
    document.write(str);
}

window.onload = function(){
    showSupport(getCanvasSupport());
};