How can I automatically scale the HTML5 <canvas> element to fit the page?
For example, I can get a <div> to scale by setting height and width to 100%, but a <canvas> won't scale, will it?
How can I automatically scale the HTML5 <canvas> element to fit the page?
For example, I can get a <div> to scale by setting height and width to 100%, but a <canvas> won't scale, will it?
If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.
You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.
You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.
Unless you want the canvas to upscale your image data automatically (that's what James Black's answer talks about, but it won't look pretty), you have to resize it yourself and redraw the image. http://stackoverflow.com/questions/1152203/centering-a-canvas/1646370#1646370
You can use CSS to scale your canvas, but not all browsers do this in a very efficient way (Chrome is much better than Firefox, for example):
<html>
<head>
<style type="text/css">
#myCanvas {
height: 100%; width: 100%; border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas">(Your browser doesn't support canvas)</canvas>
</body>
</html>
Depending on the complexity of your canvas and the frequency of your redraws, this may be simple enough for your needs. But as I mentioned, not all browsers do this very efficiently yet, so your mileage may vary.
you can use a div to get your canvas to fill the page:
<head>
<style type='text/css'>
div {position:absolute;left:0px;top:0px;width:100%;height:100%;}
</style>
</head>
<body>
<div><canvas></canvas></div>
<script type="text/Javascript">
//get div to gain access to window size
div=document.getElementsByTagName('div')[0]
//set canvas size to the whole window
canvas=document.getElementsByTagName('canvas')[0]
canvas.width=div.scrollWidth
canvas.height=div.scrollHeight
</script>
</body>
see this for example
I believe I have found an elegant solution to this:
JavaScript
/* important! for alignment, you should make things
* relative to the canvas' current width/height.
*/
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
CSS
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
Hasn't had any large negative performance impact for me, so far.