【问题标题】:Script not loading css properties from external file脚本未从外部文件加载 css 属性
【发布时间】:2021-10-12 19:11:15
【问题描述】:

这是我的 2 个文件

HTML:

<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c=document.getElementById("myCanvas");
      alert(c.width)
    </script>

  </body>

</html>

CSS:

canvas {
  width:480;
  height:360;
  position:absolute;
  background-color:grey;
}

显然,我的画布元素的宽度是 480,但由于某种原因,alert(c.width) 返回 300。

【问题讨论】:

    标签: javascript html css html5-canvas


    【解决方案1】:

    这是因为c.width 指的是元素的宽度属性。如果 canvas 元素中不存在该属性,您将获得它的默认值,即 300 像素。高度(150px)也会发生同样的情况。

    要获得真正的画布宽度,您可以使用getBoundingClientRect()。另外,不要忘记在宽度和高度的 CSS 数值后添加“px”。

    canvas {
      width: 480px;
      height: 360px;
      position:absolute;
      background-color:grey;
    }
    <html>
    
      <head>
        <link rel="stylesheet" href="style.css">
      </head>
    
      <body>
        <canvas id=myCanvas></canvas>
    
        <script>
          var c = document.getElementById("myCanvas");
          alert(c.getBoundingClientRect().width)
        </script>
    
      </body>
    
    </html>

    【讨论】:

    • 虽然这确实像预期的那样返回 480,但我仍然遇到一个问题,即绘制方法仍然认为画布是 300x150,画布渲染拉伸到 480x360。有什么办法可以解决这个问题吗?
    • 在这种情况下,您必须使用宽度和高度属性。那是因为“widthheight 属性决定了画布坐标系的宽度或高度,而 CSS 属性只决定了显示它的框的大小”,正如 SamB 在这个问题中的回答:@ 987654321@.
    【解决方案2】:

    尝试使用c.offsetWidth 而不是c.width。正如@BrunoSdoukos 已经在您尝试使用它的上下文中提到的width 要求您将宽度设置为&lt;canvas&gt; 元素上的属性,如下所示:

    <canvas id="myCanvas" width="480"></canvas>
    

    由于 HTML 元素本身没有设置宽度属性,使用c.width 将返回默认宽度,即 300 像素。

    因为您已经使用 CSS 指定了元素的宽度,以便在这种情况下获取元素宽度,所以您应该使用:

    c.offsetWidth
    

    这是 MDN 对 HTMLElement.offsetWidth 的评价:

    通常,offsetWidth 是以像素为单位的元素 CSS 宽度的度量,包括任何边框、填充和垂直滚动条(如果呈现)。它不包括伪元素的宽度,例如 ::before 或 ::after。

    你可以在这里准备更多关于这个属性的信息:

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多