Canvas on the Background

I was reading the documentation about -webkit-gradient on the Apple HTML documentation site and I stumbled across something that I had never seen before.  I thought it was so cool, that I decided to write a blog post about it.

With the introduction of CSS3 into many top-line browsers there is now the ability to manipulate the background-image of any element, specifically gradients and svg.  One of the things that is missing is canvas as an element for the background.

In 2008! WebKit introduced(http://webkit.org/blog/176/css-canvas-drawing/) a CSS attribute value called -webkit-canvas(id).  When attached to a background style allows you the developer to have programatic access to the background-image through canvas. Believe me when I say "This is Powerful".

I must warn that this is specific to WebKit only at the moment.  I would love to see other browsers add this support in as it is super powerful.

So lets see this in action.

In this post I will do one simple sample (http://html5samples.appspot.com/backgroundCanvas.html) and all it will do is draw a square into the background of a div:

  <html>
    <head>
      <style>
      div {
        background: -webkit-canvas(test);
        float:left;
        width: 100;
        height: 100;
      }
      </style>

      <script>
        function onLoad() {
          var ctx = document.getCSSCanvasContext("2d","test", 100,100);
          ctx.fillStyle = "blue";
          ctx.fillRect(10,10,90,90)
        }

        (function() {
          document.addEventListener("DOMContentLoaded", onLoad);
        })();
      </script>
    </head>
    <body>
      <div>This is a div</div>
    </body>
  </html>

Pretty cool!  Well actually the concept is cool, that demo is pretty ugly :) You can do some pretty awesome demos with this.  You could have a game or some super cool animation running in the background. I think you could get around the lack of background-opacity support in CSS3.

I will do some more samples soon.