Resizable HTML5 Canvas

24 Aug 2011

When creating a responsive website, it is important that all the content will resize properly. While working on a responsive layout, you must try to avoid pixels in your CSS. Instead of using those nasty fixed pixels, you will have to use percentages. The HTML5 Canvas element needs to have at least two inline attributes, the width and height. A third attribute, an ID, will be needed if you want to program the canvas. The canvas must have a size (width and height), which will always be defined in pixels. You can try to define these values as a percentage, but this simply doesn't work. A width of 100% will always turn out as a width of 100 pixels! So if pixels are required, and percentages don't work, we will have to change the values on runtime. This can be done with Javascript, and in this case we will use jQuery to make things easier. First things first, we need the HTML markup. HTML Markup
<div id="main" role="main">
    <canvas id="respondCanvas" width="100" height="100">
        < !-- Provide fallback -->
    </canvas>
</div> 
As you can see the default values of the width and height attributes are both set to 100. This will result in a canvas square of 100 by 100 pixels. Next up is the CSS. CSS
#main{
    display:block;
    width:80%;
    padding:50px 10%;
    height:300px;
} 
The only CSS needed for this example is that of the canvas container, in this case a div with id="main". We will make sure that the canvas is just as wide as its parent, using a bit of Javascript. Javascript (jQuery)
$(document).ready( function(){
    //Get the canvas &
    context var c = $('#respondCanvas');
    var ct = c.get(0).getContext('2d');
    var container = $(c).parent();

    //Run function when browser resizes
    $(window).resize( respondCanvas );

    function respondCanvas(){
        c.attr('width', $(container).width() ); //max width
        c.attr('height', $(container).height() ); //max height

        //Call a function to redraw other content (texts, images etc)
    }

    //Initial call
    respondCanvas();

}); 
Once the window resizes, the Javascript kicks in. It changes the width and height attributes of the canvas to match its parent. The initial values (100 by 100 pixels) will be replaced, and the canvas will respond to it. This means that content (e.g. texts, images etc) will have to be redrawn and repositioned to fit the new canvas. The initial function call will make sure the canvas fits its parent once the page is loaded. I've created a small demo page that uses the same code.

View demo

The demo includes a text which will respond to the canvas. The text is always centered (repositioned) in the middle of the canvas.

Please leave a comment if this was useful to you. You are also welcome to leave a suggestion for a future blogpost!

Thanks,
Alex Meijer