我目前正在测试使用 <canvas>
元素来绘制所有背景(稍后我会为这些图像添加效果,这也是我不使用 CSS 加载图像的原因)。也就是说,我目前很难将图像加载到画布上。这是代码:
<html>
<head>
<title>Canvas image testing</title>
<script type="text/javascript">
function Test1() {
var ctx = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
//Loading of the home test image - img1
var img1 = new Image();
img1.src = 'img/Home.jpg';
//drawing of the test image - img1
img1.onload = function () {
//draw background image
ctx.drawimage(img1, 0, 0);
//draw a box over the top
ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
ctx.fillRect(0, 0, 500, 500);
};
}
}
</script>
<style type="text/css">
canvas { border: 2px solid black; width: 100%; height: 98%; }
</style>
</head>
<body onload="Test1();">
<canvas id="canvas" width="1280" height="720"></canvas>
</body>
</html>
我认为我没有正确加载图像,但我不确定。
原文由 dee Five 发布,翻译遵循 CC BY-SA 4.0 许可协议
有几件事:
drawimage
应该是drawImage
注意大写i。getElementById
正在寻找 ID 为canvas
的元素,但它应该是test1
。canvas
是标签,不是 ID。canvas
变量(例如在您的canvas.getContext
行中)替换为ctx
,因为这是您用来选择画布元素的变量。src
之前绑定您的onload
处理程序。所以你的函数应该像这样结束: