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!
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.
<div id="main" role="main">
<canvas id="respondCanvas" width="100" height="100">
< !-- Provide fallback -->
//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 );
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
//Call a function to redraw other content (texts, images etc)
I've created a small demo page that uses the same code.
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!