我目前正在测试使用
<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>
我认为我没有正确加载图像,但我不确定。
有几件事:
drawimage
应该是 drawImage
- 注意大写 i.getElementById
正在寻找ID为canvas
的元素,但它应该是test1
。 canvas
是标签,不是 ID。canvas
变量(例如在 canvas.getContext
行中)替换为 ctx
,因为这是您用来选择画布元素的变量。onload
之前绑定您的 src
处理程序。所以你的函数应该像这样结束:
function Test1() {
var ctx = document.getElementById('test1');
if (ctx.getContext) {
ctx = ctx.getContext('2d');
//Loading of the home test image - img1
var img1 = new Image();
//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);
};
img1.src = 'img/Home.jpg';
}
}
使用较新的 JavaScript 功能:
let img = await loadImage("./my/image/path.jpg");
ctx.drawImage(img, 0, 0);
loadImage
函数如下所示:
async function loadImage(url) {
return new Promise(r => { let i = new Image(); i.onload = (() => r(i)); i.src = url; });
}
将 onload 事件侦听器移至设置图像的 src 之前。
var img1 = new Image();
//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);
};
img1.src = 'img/Home.jpg';
将本地文件资源(url)分配给图像源,并使用要加载的画布中的上下文绘制图像。就是这样。请参阅下面的代码。
var loadImage = function (url, ctx) {
var img = new Image();
img.src = url
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
}
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var img1 = new Image();
//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);
};
img1.src = 'img/Home.jpg';
<canvas id="canvas"></canvas>