HTML and CSS Reference
In-Depth Information
Canvas basics
note querySelector
and querySelectorAll
is a new DOM API that accepts
a CSS selector and returns the
elements it matches. Currently
available in all the latest brows-
ers, querySelector returns
the first DOM node it finds,
whereas querySelectorAll
returns a NodeList object that
you'll need to iterate over.
The hello world of any canvas demo starts with putting the
canvas element on your page. Initially the canvas is completely
invisible and by default is 300 pixels wide by 150 pixels high:
<!DOCTYPE html>
<title>canvas hello world</title>
<canvas></canvas>
Now that the canvas element is in place, you need to use
JavaScript to get the 2D context to allow you to draw:
var ctx = document.querySelector('canvas').getContext('2d');
Now that you have the context, you have access to the full
API to draw as you please. Add simple shapes to your canvas
( figure 5.4 ):
ctx.fillRect(10, 20, 50, 50);
fIgure 5.4 A filled rectangle
using the default settings on a
canvas.
What about browser support?
Browser support is fairly good for the canvas element; four of the big
five browsers support canvas in the latest versions of the browser (and
in fact support is fairly good in previous versions of the browsers, too).
“What about IE?” is the question that is perpetually asked.
For versions of IE that don't support canvas, you can shim canvas
support in a couple of ways. The first is via Silverlight and a library
called html5canvas ( http://blogs.msdn.com/delay/archive/2009/08/24/
using-one-platform-to-build-another-html-5-s-canvas-tag-implemented-
using-silverlight.aspx ); the second is using excanvas ( http://code.
google.com/p/explorercanvas/ ), which translates the canvas API to
Microsoft's VML.
The two libraries don't cover all of the 2D API, but most of the com-
monly used methods. Several demos show comparisons from exam-
ples in the wild. Theoretically, you could try mixing the shims together;
if Silverlight isn't available, drop support down to excanvas. I've not yet
seen this done in practice, but in theory I can't see any reason why it
wouldn't work, so long as you can detect Silverlight support.
Search WWH ::




Custom Search