import Resource from './resource' let imageCache = {} class Image { constructor (file, img) { this.file = file this.img = img } static async load (file) { if (imageCache[file]) return imageCache[file] let img = await Resource.loadImage(file) let imgCl = new Image(file, img) imageCache[file] = imgCl return imgCl } get width () { return this.img.width } get height () { return this.img.height } draw (ctx, x, y, w, h) { ctx.drawImage(this.img, x, y, w, h) } } class TileMap extends Image { constructor (file, img, xaspect, yaspect) { super(file, img) this.xaspect = xaspect this.yaspect = yaspect this.xcount = this.width / xaspect this.ycount = this.height / yaspect this.tiles = [] for (let y = 0; y < this.ycount; y++) { for (let x = 0; x < this.xcount; x++) { this.tiles.push({ x, y }) } } } draw (ctx, index, x, y, w, h) { let box = this.tiles[index] if (!box) return ctx.drawImage(this.img, box.x * this.xaspect, box.y * this.yaspect, this.xaspect, this.yaspect, x, y, w, h) } static async load (file, x, y) { if (imageCache[file]) return imageCache[file] let img = await Resource.loadImage(file, true) let imgCl = new TileMap(file, img, x, y) imageCache[file] = imgCl return imgCl } } export { Image, TileMap }