Centering a canvas

后端 未结 11 1426
野的像风
野的像风 2021-01-30 10:00

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 h

相关标签:
11条回答
  • 2021-01-30 10:59

    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/

    0 讨论(0)
  • 2021-01-30 10:59

    Simple:

    <body>
        <div>
            <div style="width: 800px; height:500px; margin: 50px auto;">
                <canvas width="800" height="500" style="background:#CCC">
                 Your browser does not support HTML5 Canvas.
                </canvas>
            </div>
        </div>
    </body>
    
    0 讨论(0)
  • 2021-01-30 11:00

    easiest way

    put the canvas into paragraph tags like this:

    <p align="center">
      <canvas id="myCanvas" style="background:#220000" width="700" height="500" align="right"></canvas>
    </p>

    0 讨论(0)
  • 2021-01-30 11:01

    Resizing canvas using css is not a good idea. It should be done using Javascript. See the below function which does it

    function setCanvas(){
    
       var canvasNode = document.getElementById('xCanvas');
    
       var pw = canvasNode.parentNode.clientWidth;
       var ph = canvasNode.parentNode.clientHeight;
    
       canvasNode.height = pw * 0.8 * (canvasNode.height/canvasNode.width);  
       canvasNode.width = pw * 0.8;
       canvasNode.style.top = (ph-canvasNode.height)/2 + "px";
       canvasNode.style.left = (pw-canvasNode.width)/2 + "px";
    
    
    }
    

    demo here : http://jsfiddle.net/9Rmwt/11/show/

    .

    0 讨论(0)
  • 2021-01-30 11:02

    As to the CSS suggestion:

    #myCanvas { 
     width: 100%;
     height: 100%;
    }
    

    By the standard, CSS does not size the canvas coordinate system, it scales the content. In Chrome, the CSS mentioned will scale the canvas up or down to fit the browser's layout. In the typical case where the coordinate system is smaller than the browser's dimensions in pixels, this effectively lowers the resolution of your drawing. It most likely results in non-proportional drawing as well.

    0 讨论(0)
提交回复
热议问题