JavaScript - 如何加载图像

时间:2017-08-09 18:20:54

标签: javascript html5 html5-canvas

想知道如何使用JS加载图像:

Maps.js

{id: 21, colour: 'res/pillar.png', solid: 1, bounce: 
0.30}, /*Loading the image in as an attribute*/

的engine.js

/*From draw_tile function*/

if (!tile || !tile.colour) return;
debugger;
context.drawImage(tile.colour, x, y);
context.fillRect(
    x,
    y,
    this.tile_size,
    this.tile_size
);

-----------------------------------

/*From draw_map function*/

this.draw_tile(t_x, t_y, this.current_map.data[y][x], context);

控制台:

tile.colour
"res/pillar.png"

属性正在运作。

但是得到这个错误 - context.drawImage()

Engine.js:173 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
at Engine.draw_tile (Engine.js:173)
at Engine.draw_map (Engine.js:199)
at Engine.draw (Engine.js:450)
at Loop (index.html:87)
at index.html:94

我可能很难做到这一点,或者我只是遗漏了一些东西,但是如何以我编码的方式加载图像?我也相信我可能需要一个onload()但是在哪里?

安迪

1 个答案:

答案 0 :(得分:0)

  

提供的值不是'(CSSImageValue或HTMLImageElement)类型   或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或   ImageBitmap或OffscreenCanvas)'

错误告诉您drawImage需要一个Image(或其他几个选项) - 而不是字符串:

var imgTile = new Image();
imgTile.src = tile.colour;
imgTile.onload = function() {
   context.drawImage(imgTile, x, y)
}