代码之家  ›  专栏  ›  技术社区  ›  teraspora

基本HTML页面中的画布大小始终为300x150。

  •  1
  • teraspora  · 技术社区  · 7 年前

    <canvas> 元素:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
    
        <style>
          body {
            border: 1px solid #ff5500;
            background-color: black;
          }
          canvas {
            width: 100%;
            height: 100%;
          }
        </style>
    </head>
    
    <body>
     <canvas id="canv" style='width:1024px;height:768px'>
      </canvas>
    </body>
    
    </html>
    

    但不管我怎么设定 width height (使用像素、百分比或视口单位),无论是否设置样式(例如。 style='width:1024px;height:768px' ),不管我如何调整浏览器窗口的大小,开发人员控制台总是报告宽度x高度为300x150。为什么会这样,我该怎么处理?

    var c = document.getElementById("canv");
    undefined
    c.style.width
    "1024px"
    c.style.height
    "768px"
    c.width
    300
    c.height
    150
    

    Chromium和Firefox都有相同的行为。

    我已经拖网了堆栈溢出和web的一般情况,发现了它们之间的很多区别 宽度 clientWidth

    2 回复  |  直到 7 年前
        1
  •  2
  •   Jerdine Sabio    7 年前

    我想你指的宽度和高度是 html属性 而不是css。

    它们可以这样修改;

    <canvas width="1024" height="768" style="border:1px solid black;">
    </canvas>
        2
  •  3
  •   dscham    7 年前

    你必须改变canv.宽度或者直接在HTML中设置属性。不需要任何CSS或JS。

    例子:

    var can = document.querySelector("#testC");
    var can2 = document.querySelector("#testC2");
    
    console.log("Canvas before JS: ", can.width, "x", can.height);
    console.log("Canvas in HMTL: ", can2.width, "x", can2.height);
    
    can.width = 600;
    can.height = 600;
    
    console.log("Canvas after JS: ", can.width, "x", can.height);
    console.log("Canvas in HMTL: ", can2.width, "x", can2.height);
    <canvas id="testC" width="300" height="300">
    <canvas id="testC2" width="600" height="600">

    Canvas before JS: 300x300
    Canvas in HMTL: 600x600
    Canvas after JS: 600x600
    Canvas in HMTL: 600x600
    
    推荐文章