How do I markup a page with an HTML5 canvas
such that the canvas
Takes up 80% of the width
Has a corresponding pixel height and width which effectively define the ratio (and are proportionally maintained when the canvas is stretched to 80%)
Is centered both vertically and horizontally
You can assume that the canvas
is the only thing on the page, but feel free to encapsulate it in div
s if necessary.
To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned.
This will center the canvas horizontally:
#canvas-container { width: 100%; text-align:center; } canvas { display: inline; }
HTML:
<div id="canvas-container"> <canvas>Your browser doesn't support canvas</canvas> </div>
Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.
Center canvas to middle of the screen or parent element. No wrapping.
HTML:
<canvas id="canvas" width="400" height="300">No canvas support</canvas>
CSS:
#canvas { position: absolute; top:0; bottom: 0; left: 0; right: 0; margin:auto; }
Javascript:
window.onload = window.onresize = function() { var canvas = document.getElementById('canvas'); canvas.width = window.innerWidth * 0.8; canvas.height = window.innerHeight * 0.8; }
Works like a charm - tested: firefox, chrome
fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With