How to get a responsive canvas tag

  Read comments... Posted on 1st February 2014

Summary
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 chaart 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 resize. 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 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.

<script>
    $(document).ready(function ()
    {
        var canvas = document.getElementById("cvs");

        RGraph.Reset(canvas);

        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: {
                labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
                textSize: text_size,
                gutterBottom: 35,
                linewidth: linewidth,
                tickmarks: 'endcircle',
                shadow: true,
                hmargin: 5
            }
        }).draw();
    });
</script>
    

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>
Share RGraph
X

Comments