import { TILE_SIZE } from "../constants.js"; import { createCanvas } from "../utils.js"; import { GameObject } from "./game-object.js"; export class Map extends GameObject { constructor({ name, imageId, elementId, selected = false }) { super(); this.name = name; this.imageId = imageId; this.image = document.getElementById(imageId); this.width = this.image.width; this.selected = selected; this.elementId = elementId; } async load() { const levelConfig = await fetch("/resources/" + this.name + ".json"); this.levelConfig = await levelConfig.json(); } get level() { if (this._level) { return this._level; } const levelConfig = this.levelConfig; const layer = levelConfig.layers[0]; const { data, height, width } = layer; const { ctx, canvas } = createCanvas(width * TILE_SIZE, height * TILE_SIZE); for (let row = 0; row < height; row++) { for (let col = 0; col < width; col++) { if (row < 0 || col < 0 || row >= height || col >= width) continue; const tile = data[row * width + col] - 1; ctx.drawImage( this.image, (tile * TILE_SIZE) % this.width, Math.floor((tile * TILE_SIZE) / this.width) * TILE_SIZE, TILE_SIZE, TILE_SIZE, col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE ); } } return (this._level = canvas); } render(ctx, sourceX, sourceY, width, height) { if (!this.levelConfig || !this.selected) { return; } ctx.drawImage( this.level, sourceX, sourceY, width, height, 0, 0, width, height ); } }