【问题标题】:Image not filling canvas when dims are not specified [duplicate]未指定暗淡时图像未填充画布[重复]
【发布时间】:2020-06-07 09:23:48
【问题描述】:

我想动态创建一个画布,在运行时指定画布的尺寸;然后我想在该画布上渲染一个图像,以便它填充画布的整个尺寸。

当我在 <canvas> 元素上声明画布的宽度和高度时,这可以按预期工作,如以下 sn-p 所示(默认隐藏):

<!DOCTYPE html>
<html>

<body>

  <h3>
    Source Image
  </h3>
  <img id="image" src="http://placehold.it/180x180">

  <h3>Canvas:</h3>
  <canvas id="canvas" width="200" height="200" style="border:1px solid #d3d3d3;">
</canvas>

  <script>
    window.onload = function() {
      var c = document.getElementById("canvas");
      var ctx = c.getContext("2d");
      var img = document.getElementById("image");
      ctx.drawImage(img, 10, 10);
    }
  </script>

</body>

</html>

但是,如果我使用 Javascript 动态创建 &lt;canvas&gt; 元素,并在创建后使用 CSS 设置大小,则图像不会填满整个画布:

<!DOCTYPE html>
<html>

<body>

  <h3>
    Source Image
  </h3>
  <img id="image" src="http://placehold.it/180x180">

  <h3>Canvas:</h3>
  <canvas id="canvas" style="border:1px solid #d3d3d3;">
</canvas>

  <script>
    window.onload = function() {
      var c = document.getElementById("canvas");
      c.style.width = "200px";
      c.style.height = "200px";
      var ctx = c.getContext("2d");
      var img = document.getElementById("image");
      ctx.drawImage(img, 10, 10);
    }
  </script>

</body>

</html>

我觉得我在这里遗漏了一些非常明显的东西——任何关于如何让动态渲染的 Canvas 看起来像第一个 sn-p 的帮助都将不胜感激。

【问题讨论】:

    标签: javascript html css html5-canvas


    【解决方案1】:

    通过使用c.style.width,您定义了在屏幕上显示它的比例(它只是 CSS)。

    要实际设置画布的固有大小,请执行以下操作:

    window.onload = function() {
      var c = document.getElementById("canvas");
      c.width = 200;
      c.height = 200;
      var ctx = c.getContext("2d");
      var img = document.getElementById("image");
      ctx.drawImage(img, 10, 10);
    }
    <h3>Source Image</h3>
    <img id="image" src="http://placehold.it/180x180">
    
    <h3>Canvas:</h3>
    <canvas id="canvas" style="border:1px solid #d3d3d3;"></canvas>

    注意:这并不妨碍您拥有不同的固有尺寸和显示尺寸。事实上,如果您的页面显示在具有高像素密度的 Retina 屏幕上,这通常很有用。在这种情况下,您可以拥有一个 200x200 的画布,并将其 CSS 尺寸设置为 100x100。这样,画布中的每个像素都将恰好是它所显示屏幕的 1 个像素。

    More info on window.devicePixelRatio如果你有兴趣。

    【讨论】:

    • 感谢您的快速回复!
    • @Edward Q. Bridges:如果占位图像是 360x360 且 180px 是您的设计要求,该怎么办?将img { width: 180px } 添加到您的css 并在调试器中检查height / clientheight / naturalheight 看看会发生什么...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    相关资源
    最近更新 更多