HTML and CSS Reference
In-Depth Information
You may be more interested to see
what the page looks like in a
browser that does support <canvas> .
If you're wondering where all the
whizzy graphics promised in the
introduction are, well, they don't
appear by magic. To create pictures
with <canvas> , there needs to be a
JavaScript program that tells the
browser what to draw.
Before you get to drawing something, you need to understand a couple
of things. You need to know how to get a reference to your canvas object
so you can send it drawing commands; and, because you'll be telling the
<canvas> element to draw shapes on a grid, you need to know how the
grid is defined. First, here's how to get a reference in JavaScript:
function draw() {
var canvas = document.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
//do stuff
window.addEventListener("load", draw, false);
Add this code between <script> tags in the <head> of an HTML docu-
ment containing a <canvas> element like that shown in the first listing in
this section. In the following sections, you'll update the draw() function
to create graphics. If you're confused about what this document should
look like, please download the code samples from
crowther/ and look at the file ch03/canvas-1.html.
You have to pass a parameter, 2d , to the getContext method. This gives
you a two dimensional drawing context. Currently this is the only
parameter supported. Several browser vendors are experimenting
with a three dimensional drawing context with direct access to
graphics hardware, which will open up possibilities such as 3D
games, virtual reality experiences, and modeling tools.
Search WWH ::

Custom Search