简体   繁体   English

JavaScript-如何加载图像

[英]JavaScript - How to load images

Just wondering how I would load an image using JS like this: 只是想知道如何使用JS这样加载图像:

Maps.js Maps.js

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

Engine.js 的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);

Console: 安慰:

tile.colour
"res/pillar.png"

Attribute is working. 属性正在工作。

But get this error on - context.drawImage() 但是在-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

I'm probably poorly going about this or that I am just missing something, but how do I load the image in the way I am coding? 我可能做得不好,或者我只是缺少一些东西,但是如何以编码方式加载图像? I also believe I may need an onload() but where? 我也相信我可能需要onload(),但是在哪里?

Andy 安迪

The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)' 提供的值不是'(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)类型的值

The error is telling you that drawImage expects an Image (or a few other options) - not a string: 该错误告诉您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