I'm trying to load images from my array using the drawImage canvas method. The problem is that it sometimes throws me the following error
Uncaught (in promise) DOMException: An attempt was made to use an object that is not, or is no longer, usable
↑ firefox ↓ google
Uncaught (in promise) DOMException: Failed to execute 'createImageBitmap' on 'Window': The source image width is 0.
Both on index.js:13
Sometimes if I load the page again the error disappears. Does anyone know what could be causing this problem?
My code:
(async () => {
const img = new Image();
img.src = "./img/BOE_tile_set.png";
let tiles = [];
let tileWidth = 28;
let tileHeight = 36;
for (let i = 0; i < 77; i++) {
let x = i % 8;
let y = Math.floor(i / 8);
let bmp = await createImageBitmap(img, x * tileWidth, y * tileHeight, tileWidth, tileHeight); // index.js:13
tiles.push({
bmp,
x,
y
})
}
const canvas = document.querySelector("canvas");
canvas.width = 224; // img.width
canvas.height = 360; // img.height
const ctx = canvas.getContext("2d");
draw();
function draw() {
tiles.forEach((tile) => {
ctx.drawImage(tile.bmp, tile.x * tileWidth, tile.y * tileHeight);
})
}
})();