繁体   English   中英

JavaScript-如何加载图像

[英]JavaScript - How to load images

只是想知道如何使用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(),但是在哪里?

安迪

提供的值不是'(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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM