<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();
});
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