An example of using another canvas with the HTML5 canvas drawImage function

[No canvas support]

[No canvas support]

As well as being able to use the drawImage function in canvas to show both an image and also a video (see the link below) another ability that it has is show another canvas as it is at the time that the drawImage function is called.

The example has two canvas tags - the top one is a normal RGraph chart and the second is the result of a little bit of JavaScript that does a drawImage call. Instead, though, of using an image as its source it uses the first canvas, which has the chart on it. So this results in the chart being used as the image and is drawn on to the second canvas.

As with regular images you can specify the width and height arguments to the drawImage call, which has been done, so this results in the chart being shown at half size.


The HTML code:

<div style="float: right; border: 1px solid #eee; text-align: center; width: 600px">
    <canvas id="cvs1" width="600" height="250">[No canvas support]</canvas><br /><br />
    <canvas id="cvs2" width="300" height="125">[No canvas support]</canvas>
</div>

The JavaScript code:

<script>
    window.onload = function (e)
    {
        /**
        * Draw the first chart
        */
        var bar = new RGraph.Bar('cvs1', [4,8,5,6,2,3,1,5,6,8])
            .set('labels', ['John','Lou','Pete','Abel','Kane','Kevin','Hoolio','Max','Geoff','Rachel'])
            .draw();
        
        /**
        * Now that the chart has been drawn we can use it as a source to the second canvas' drawImage() call
        * and draw it at half size
        */
        context = document.getElementById('cvs2').getContext('2d');
        context.drawImage(bar.canvas, 0, 0, 300,125);
    }
</script>

Related pages