HTML5 in Gadgets on iGoogle

Wednesday, May 26, 2010 at 2:26 PM

Did you know gadgets can use html5? The key is in the doctype. Normally the doctype of a gadget isn't mentioned. Specify the html5 doctype in the gadget and it will be used when the gadget is rendered. Let's look at a quick example using the popular canvas drawing API:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
 <ModulePrefs title="html5 canvas">
 </ModulePrefs>
 <Content type="html" view="home,canvas">
  <![CDATA[
   <!DOCTYPE html>
   <script>
    var demo = {
     init: function() {
      var drawcan = document.getElementById('drawarea');
      if (drawcan.getContext){
       var context = drawcan.getContext('2d');
       var xmax = drawcan.width;
       var ymax = drawcan.height;
       context.strokeRect(0,0,xmax,ymax);
       for (var dotix = 0; dotix < 100; ++dotix) {
        var x = Math.random() * xmax;var y = Math.random() * ymax;
        context.strokeStyle = "#888888";
        var blueness = Math.floor(Math.random() * 256);
        context.fillStyle = "rgb(10,90,"+ blueness +")";
        context.beginPath();
        context.arc(x,y,5,0,Math.PI*2,true);
        context.closePath();
        context.stroke();
        context.fill();
       }
      }
     }
    };
  
    gadgets.util.registerOnLoadHandler(demo.init);
 
   </script>
   <canvas id="drawarea" width="150" height="150"></canvas>
  ]]>
 </Content>
</Module>




The top of the gadget still has the usual XML prolog because the gadget spec is, as always, an XML document. The html, in this case html5, is inside a CDATA block. The CDATA block means the structure of the html5 content is pretty much ignored when parsing the XML. iGoogle doesn't do anything extra for compatibility with html5; features specific to html5 will still only work in browsers that support them. Gadgets have the same cross-browser compatibility concerns as any other web page. Have a look at the When can I use guide for an idea of compatibility of features across browsers.

The content of this gadget is pretty straightforward. It includes a canvas element. In the init method it tries to get a drawing context. If it's successful (meaning the browsers supports html5 canvas) it will draw a rectangle around the extents of the element then draw 10 randomly placed dots inside. Use this gadget as a starting point to get your own html5 gadget running.

And yes, this gadget has a canvas in your canvas so you can render when you render.