【发布时间】: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