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

Written by Richard Heyes, on 1st July 2014

As well as images and video the drawImage() function can also have another canvas given to it. This feature can be used to clone a canvas for example.

[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 to 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 of using an image as its source though, 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 here, 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>

The JavaScript code:

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

Related pages