Javascript drawImage() 不在 HTML 画布中显示图像

问题描述 投票:0回答:1

在我将图像放置在画布中的简单测试代码(HTML 和 Javascipt)中,drawImage() 不起作用。图像是在 HTML 页面中创建的,而不是在画布中创建的。代码是:

<html>
  <body>
    <img id = "myImg" src = "testImg.JPG" alt="Cannot find image" width="100" height="100">
    <canvas id = "myCanvas" width="150" height="175" style = "border:5px solid #000000;"></canvas>
    <script>
      const canvas = document.getElementById("myCanvas");
      const img = document.getElementById("myImg");
      const ctx = canvas.getContext("2d");

      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

      function showPics(){
        ctx.fillStyle = "red";
        ctx.fillRect(0,0,50,50);
      }

      showPics();
    </script>
  </body>
</html>

在Win10 Firefox中,打开HTML文件后,图像显示在HTML页面中,但不显示在画布中。如果我刷新,图像确实会出现在页面和画布中。 在我的 Android 6 手机中,图像出现在 HTML 页面中,但从未出现在画布中。 Win10火狐浏览器截图为: [enter image description here](https://i.stack.imgur.com/g8gkx.png)

我的印象是,即使图像文件与html代码位于同一文件夹中,javascript代码也找不到图像文件。

在Win10 Firefox中,refresh是做什么来允许javascript访问图像文件的? 在Android 6中,为什么根本找不到它?

javascript drawimage
1个回答
0
投票

@Mike 感谢您指出我确保图像已加载。以下代码有效。

<html>
<body>
<img id = "myImg" src = "testImg.JPG" alt="Cannot find image" 
onload = "showPics()" width="100" height="100">
<canvas id = "myCanvas" width="150" height="175" style = "border:5px solid #000000;"></canvas>
<script>
function showPics(){
const canvas = document.getElementById("myCanvas");
const img = document.getElementById("myImg");
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(0,0,50,50);
}
</script>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.