views:

1579

answers:

3
+2  Q: 

Centering a 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 s if necessary.

+1  A: 

Given that canvas is nothing without JavaScript, use JavaScript too for sizing and positionning (you know: onresize, position:absolute, etc.)

Thomas Broyer
Could you provide a code example please?
+2  A: 

Tested only on Firefox:

<script>
window.onload = window.onresize = function() {
    var C = 0.8;        // canvas width to viewport width ratio
    var W_TO_H = 2/1;   // canvas width to canvas height ratio
    var el = document.getElementById("a");

    // For IE compatibility http://www.google.com/search?q=get+viewport+size+js
    var viewportWidth = window.innerWidth;
    var viewportHeight = window.innerHeight;

    var canvasWidth = viewportWidth * C;
    var canvasHeight = canvasWidth / W_TO_H;
    el.style.position = "fixed";
    el.setAttribute("width", canvasWidth);
    el.setAttribute("height", canvasHeight);
    el.style.top = (viewportHeight - canvasHeight) / 2;
    el.style.left = (viewportWidth - canvasWidth) / 2;

    window.ctx = el.getContext("2d");
    ctx.clearRect(0,0,canvasWidth,canvasHeight);
    ctx.fillStyle = 'yellow';
    ctx.moveTo(0, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, 0);
    ctx.lineTo(canvasWidth, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, canvasHeight);
    ctx.lineTo(0, canvasHeight/2);
    ctx.fill()
}
</script>

<body>
<canvas id="a" style="background: black">
</canvas>
</body>
Nickolay
http://jsfiddle.net/FUCur/
Mark
A: 

Wrapping it with div should work. I tested it in Firefox, Chrome on Fedora 13.

<style type="text/css">
    #content {
        width: 95%;
        height: 95%;
        margin: auto;
    }
    #myCanvas {
        width: 100%;
        height: 100%;
        border: 1px solid black;
    }
</style>

And the canvas should be enclosed in tag

<div id="content">
    <canvas id="myCanvas">Your browser doesnt support canvas tag</canvas>
</div>

Let me know if it works. Cheers.

Sainath Mallidi
http://jsfiddle.net/p4BEs/
Sainath Mallidi