它没有显示图像,我尝试了所有可能的方法,我无法弄清楚如何。我该怎么做:
1)如何创建新的对象对象('20','X',250,100,'img');并指定我想要使用哪张图片? img.player或img.player.src还是只是img? 2)如何遍历objectArray在画布中全部显示它们?
15index.html: 38 Uncaught TypeError: Failed to execute 'drawImage'
on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script>
var WIDTH = 500;
var HEIGHT = 500;
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var img = {};
img.player = new Image();
img.player.src = "FireMonster.png"
var objectArray = {};
function object(id, name, x, y, img) {
var object3 = {
x: x,
y: y,
name: name,
id: id,
img: img,
};
objectArray[id] = object3;
}
object('20', 'X', 250, 100, 'img');
object('21', 'P', 150, 150, 'img');
drawingObject = function(something) {
ctx.drawImage(something.img, something.x, something.y);
}
update = function() {
for (var x in objectArray) {
drawingObject(objectArray[x]);
}
}
setInterval(update, 40);
</script>
</body>
</html>
答案 0 :(得分:1)
您正在将'img'
的文字传递给object
function
而不是Image
个对象。试试这个:
object('20', 'X', 250, 100, img.player);
object('21', 'P', 150, 150, img.player);