【问题标题】:Why won't my image draw to canvas unless there is an instance of the image in the html?除非 html 中有图像的实例,否则为什么我的图像不会绘制到画布上?
【发布时间】:2021-04-06 09:02:56
【问题描述】:

我有一个画布元素、上下文 2d 和一个我希望能够在它们之间切换的图像源列表。目前,唯一绘制的图像是已经加载到 html 中的图像,其他图像根本没有绘制到画布上,但是当我 console.log 时,图像将显示图像对象,但它仍然没有绘制。我之前还画了一个测试矩形,以确保画布正常工作,并且矩形画得很好。这是我的代码。

HTML:

<!DOCTYPE html>
<html lang="en">

<head>

    <title>Card Test</title>
</head>

<body>
    <canvas class="canvas" height="700" width="700" style="background-color: #3e3e3e"></canvas>

</body>

<img width="100" height="200" src="/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/3C.png">



<script type="text/javascript" src="draw.js"></script>

</html>

Javascript (draw.js):

const canvas = document.querySelector(".canvas");

var imageObj = new Image();

const ctx = canvas.getContext("2d");

const images = [
    '/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/2C.png',
    '/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/3C.png',
    '/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/4C.png',
    '/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/5C.png',
    '/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/6C.png',
    '/Users/Charlie 1/Desktop/Coding/Webpage Projects/TestWithCards/PNG/7C.png'
];

window.onload = function() {

    console.log('test1');
    imageObj.width = 100;
    imageObj.height = 200;
    imageObj.src = images[4]; // EX. Only images[1] will load because I have it loaded in the html

    console.log(imageObj);

    ctx.drawImage(imageObj, 50, 50);

    console.log('test2');
}

【问题讨论】:

  • 在 javascript 中,设置图像的 src 只会启动加载过程。该图像无法立即使用。加载后尝试绘制图像,使用onload (参见stackoverflow.com/a/12355031/2740650)。

标签: javascript html image canvas


【解决方案1】:

在您尝试在画布上绘制图像之前,等待图像通过事件侦听器加载。

const images = [
  'https://picsum.photos/100/200?random=1',
  'https://picsum.photos/100/200?random=2',
  'https://picsum.photos/100/200?random=3',
  'https://picsum.photos/100/200?random=4',
  'https://picsum.photos/100/200?random=5',
];

var imageObj = new Image();
imageObj.width = 100;
imageObj.height = 200;
imageObj.src = images[4];
imageObj.addEventListener("load", () => {
  const canvas = document.querySelector(".canvas");
  const ctx = canvas.getContext("2d");
  ctx.drawImage(imageObj, 50, 50);
});
canvas {
  background-color: #3e3e3e;
}
&lt;canvas class="canvas" height="700" width="700"&gt;&lt;/canvas&gt;

【讨论】:

  • 完美!那行得通!太感谢了。我刚用imageObj.onload = function() { ctx.drawImage(imageObj, 50, 50, 100, 200); }
  • 是的,这也有效。乍一看文档,我认为它已被弃用,但看起来它仍然受支持。酷。
猜你喜欢
  • 2018-10-20
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2013-10-28
  • 2013-11-21
相关资源
最近更新 更多