The canvas element

The canvas element is the html tag where all the fun begins! You simply add this tag to your page and then you can get a reference to it, get the 2D context and then start using the api to draw on the canvas. You can add the tag to your page like this:

<!-- These are the  default width and height settings -->
<canvas id="cvs" width="300" height="150">[No canvas support]</canvas>

And then you can get a reference to it like this:

    window.onload = function ()
        // Get a reference to the HTML tag as with any other HTML element
        var canvas  = document.getElementById('cvs');
        // Get a reference to the canvas tag 2D drawing context. This is where all the drawing commands and
        // settings are
        var context = canvas.getContext('2d');

The getContext function returns you the 2D context - this is the object on which all the functions and properties are located. There is a WebGL context for 3D drawing - but that's beyond the scope of this reference (and also significantly more complicated to use!).

Setting the canvas width and height

To set the canvas width and height you must use the html width and height attributes. You can use css if you wish but if you do then the canvas will be scaled up from the html dimensions to fit the css dimensions - so your canvas will look blocky and blurry.