简体   繁体   中英

JavaScript - How to load images

Just wondering how I would load an image using JS like this:

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);

Console:

tile.colour
"res/pillar.png"

Attribute is working.

But get this error on - 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?

Andy

The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

The error is telling you that drawImage expects an Image (or a few other options) - not a string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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