How to center canvas in html5

后端 未结 9 1465
自闭症患者
自闭症患者 2020-12-12 11:02

I\'ve been searching for a solution for a while now, but haven\'t found anything. Maybe it\'s just my search terms. Well, I\'m trying to make the canvas center according to

相关标签:
9条回答
  • 2020-12-12 11:33

    Use this code:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .text-center{
        text-align:center;
        margin-left:auto;
        margin-right:auto;
    }
    </style>
    </head>
    <body>
    
    <div class="text-center">
    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
    Your browser does not support the HTML5 canvas tag.
    </canvas>
    </div>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-12 11:44

    The above answers only work if your canvas is the same width as the container.

    This works regardless:

    #container {
      width: 100px;
      height:100px;
      border: 1px solid red;
      
      
      margin: 0px auto;
      text-align: center;
    }
    
    #canvas {
      border: 1px solid blue;
      width: 50px;
      height: 100px;
      
    }
    <div id="container">
      <canvas id="canvas" width="100" height="100"></canvas>
    </div>

    0 讨论(0)
  • 2020-12-12 11:46

    Just center the div in HTML:

      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
         border: 1px solid red;
       }
    
    
    <div id="test">
       <canvas width="100" height="100"></canvas>
    </div>
    

    Just change the height and width to whatever and you've got a centered div

    http://jsfiddle.net/BVghc/2/

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