The canvas element

Share RGraph:   Share or Like RGraph on Facebook!

The canvas element is the HTML tag where all the fun begins! You simply add this tag to your page and the 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 -->
<canvas id="cvs" width="300" height="150">[No canvas support]</canvas>

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

<script>
    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 tags 2D drawing context. This is where all the drawing commands and
        // settings are
        var context = canvas.getContext('2d');
    }
</script>

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

[No canvas support]
A scaled up canvas because the dimensions are given by CSS instead of the HTML attributes

To set the canvas width and height you must use the HTML width/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 like this example.


© Copyright Richard Heyes 2008-2017