大家好我目前正在测试使用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>
我认为我没有正确加载图像,但我不确定。
答案 0 :(得分:17)
有一些事情:
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';
}
}
答案 1 :(得分:8)
使用较新的JavaScript功能:
let img = await loadImage("./my/image/path.jpg");
ctx.drawImage(img, 0, 0);
并且loadImage
函数如下所示:
function loadImage(url) {
return new Promise(r => { let i = new Image(); i.onload = (() => r(i)); i.src = url; });
}
答案 2 :(得分:7)
在为图像设置src之前移动onload事件侦听器。
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';
答案 3 :(得分:4)
将本地文件资源(url)分配给图像源,并使用要加载的画布的上下文绘制图像。而已。见下面的代码。
var loadImage = function (url, ctx) {
var img = new Image();
img.src = url
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
}
答案 4 :(得分:0)
var c = document.getElementById("canvas");
var ctx = 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