簡體   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