How to get a responsive canvas tag

Written by Richard Heyes, on 1st February 2014

An explanation of how to get a responsive canvas tag by using CSS to size it (ie the width and height properties)

[No canvas support] [No canvas support]

Right off the bat it has to be said that the canvas tag isn't particularly responsive. The dimensions of the canvas are specified using the HTML width and height attributes. You can specify the CSS width and/or height but that will give the appearance of a zoomed canvas and it won't actually increase the number of pixels that you have to play with.

The bottom canvas on the right is set to do this. Its width and height attributes are set to 600 and 250 respectively and then the CSS width is set at 60%. The result is a canvas that resizes when you resize the window (horizontally). It should be noted that when you set the CSS width or height it doesn't cause the canvas to be cleared - so you don't have to redraw the chart like you do if you change the width/height attributes.

The top canvas on the other hand avoids CSS and uses the window.onresize event to handle the resizing. Using JavaScript means that you can set the HTML width and height attributes and that means that the number of pixels on the canvas that you have available actually changes. If you choose this route then you also need to handle the resizing of the text too - otherwise it will remain at the default 12pt and will look too large (or small) for the resulting canvas.

One thing that you may notice is that with CSS resizing the text becomes less readable when resizing to smaller sizes.

An example of using JavaScript to resize the canvas tag

Note that this method also uses jQuery.

    $(document).ready(function ()
        var canvas = document.getElementById("cvs");


        canvas.width  = $(window).width() * 0.6;
        canvas.height = $(window).width() * 0.25;
        var text_size = Math.min(12, ($(window).width() / 1000) * 10 );
        var linewidth = $(window).width() > 500 ? 2 : 1;
            linewidth = $(window).width() > 750 ? 3 : linewidth;

        // Reset the translation fix so that it gets applied again
        canvas.__rgraph_aa_translated__ = false;
        var line = new RGraph.Line({
            id: 'cvs',
            data: [4,8,6,6,3,3,5,1,4,8,6,5,9],
            options: {
                xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
                textSize: text_size,
                marginBottom: 35,
                linewidth: linewidth,
                tickmarksStyle: 'endcircle',
                shadow: true,
                hmargin: 5

An example of using CSS to resize the canvas tag

<canvas id="cvs" width="600" height="250" style="width: 60%; float: right"<[No canvas support]</canvas>