【问题标题】:cannot center align canvas无法居中对齐画布
【发布时间】:2016-07-03 12:39:09
【问题描述】:

我一直在谷歌搜索无济于事的解决方案。我只想center-align我的canvas。 我试过float="center"text-align="center"margin-top: 100px 但我的舞台没有在浏览器中对齐中心。 任何帮助表示赞赏。

<body onLoad="Main();">
<canvas id="Shooter" width="320" height="480" align="center">
Your browser does not support the HTML5 canvas tag.
</canvas>

【问题讨论】:

    标签: html canvas alignment center


    【解决方案1】:

    您可以通过以下方式将其居中对齐:

    #Shooter {
      margin: auto;
      display: block;
    }
    

    确保父容器的宽度为 100%。

    这是一支笔。 http://codepen.io/asim-coder/pen/aNpWoB

    【讨论】:

    • 嗨,阿西姆,非常感谢。我试过了,它终于奏效了。你能告诉我为什么“margin: auto;”让它工作吗?非常感谢
    • @herblackcat。自动边距将告诉浏览器通过均匀划分画布未使用的任何空间来均匀填充左右边距 == 居中!
    • @herblackcat 希望你明白为什么margin:auto 有效(感谢markE)。如果一切顺利,您总是可以接受答案。
    【解决方案2】:

    我同意 Käsebrot 的观点,您应该将 html 编码与 css 分开,打开 style.css 文件并将其连接到“head”部分链接 rel="stylesheet" href="style.css" 中的 html 页面,然后提供您的画布 css 属性。 要使画布居中,您只需要为 margin 和 display 属性指定值。

    canvas#Shooter {
        
      margin: 0 auto;
      display: block;
      width: 320px;
      height: 480px;
            
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Title of the document</title>
        <link rel="stylesheet" href="style.css"> 
      </head>
    
      <body onLoad="Main();">
        <canvas id="Shooter">
          Your browser does not support the HTML5 canvas tag.
        </canvas>
      </body>
    
    </html>

    【讨论】:

    • 您好 Daniel、Sivan 和 Kasebrot,非常感谢您的建议。我会多练习
    【解决方案3】:

    我建议您从画布中删除 widthheightalign 标记。而是将样式区域添加到您的 html 并为画布定义 css 样式:

    <style>
        canvas {
            padding-left: 0;
            padding-right: 0;
            margin-left: auto;
            margin-right: auto;
            display: block;
            width: 320px;
            height: 480px;
        }
    </style>
    

    您的画布将如下所示:

    <canvas id="Shooter">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 2017-11-14
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多