DWE.Image = {} DWE.Image.Image = function (src) { this.src = src this.img = new Image() this.img.src = this.src this.width = 0 this.height = 0 this.loaded = false this.errored = false this.img.onload = () => { this.loaded = true this.width = this.img.width this.height = this.img.height if (this['onload']) { this.onload.apply(this, []) } } this.img.onerror = (e) => { this.loaded = false this.errored = true if (this['onerror']) { this.onerror.apply(this, [e]) } } } DWE.Image.TileMap = class TileMap extends DWE.Image.Image { constructor (src, aspectWidth, aspectHeight) { super(src) this.aspectWidth = aspectWidth this.aspectHeight = aspectHeight this.tiles = [] } onload () { for (let y = 0; y < this.height / this.aspectHeight; y++) { for (let x = 0; x < this.width / this.aspectWidth; x++) { this.tiles.push(new DWE.Math.Vector2(x, y)) } } if (this['onready']) { this.onready.call(this, this) } } draw (ctx, index, x, y, w, h) { let box = this.tiles[index] if (!box) return ctx.drawImage(this.img, box.x * this.aspectWidth, box.y * this.aspectHeight, this.aspectWidth, this.aspectHeight, x, y, w, h) } } // Load an array of image URLs // Returns a Promise DWE.Image.loadImageArray = function (uris) { return new Promise(function (resolve, reject) { let loaded = 0 let toLoad = uris.length let images = [] function loadNext(index) { let uri = uris[index] let img = new DWE.Image.Image(uri) img.onload = function () { images.push(img) loaded++ if (loaded == toLoad) resolve(images) else loadNext(loaded) } img.onerror = function (e) { reject(e) } } loadNext(loaded) }) }