Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering a canvas

Tags:

html

css

canvas

How do I markup a page with an HTML5 canvas such that the canvas

  1. Takes up 80% of the width

  2. Has a corresponding pixel height and width which effectively define the ratio (and are proportionally maintained when the canvas is stretched to 80%)

  3. 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 divs if necessary.

like image 396
user122147 Avatar asked Jul 20 '09 07:07

user122147


People also ask

How do I center my canvas?

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.


2 Answers

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> 
like image 84
Ali OKTAY Avatar answered Oct 20 '22 04:10

Ali OKTAY


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/

like image 32
Daniel Avatar answered Oct 20 '22 06:10

Daniel