How can I automatically scale the HTML5 <canvas>
element to fit the page?
For example, I can get a <div>
to scale by setting the height
and width
properties 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 the height
and width
properties to 100%, but a <canvas>
won't scale, will it?
CSS
JavaScript
A pure CSS approach adding to solution of @jerseyboy above.
Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).
Link to the example: http://temporaer.net/open/so/140502_canvas-fit-to-window.html
But take care, as @jerseyboy states in his comment:
I'm using sketch.js so after I run the init command for the canvas i change the width and height with jquery. It bases the dimensions on the parent element.
I believe I have found an elegant solution to this:
JavaScript
CSS
Hasn't had any large negative performance impact for me, so far.
Basically what you have to do is to bind the onresize event to your body, once you catch the event you just need to resize the canvas using window.innerWidth and window.innerHeight.