59 lines
1.5 KiB
JavaScript
59 lines
1.5 KiB
JavaScript
import { COLS, ROWS, 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 { ctx, canvas } = createCanvas(COLS * TILE_SIZE, ROWS * TILE_SIZE);
|
|
|
|
const image = this.image;
|
|
const width = this.width;
|
|
const level = this.levelConfig;
|
|
const layer = level.layers[0];
|
|
const data = layer.data;
|
|
|
|
for (let row = 0; row < ROWS; row++) {
|
|
for (let col = 0; col < COLS; col++) {
|
|
const tile = data[row * COLS + col] - 1;
|
|
ctx.drawImage(
|
|
image,
|
|
(tile * TILE_SIZE) % width,
|
|
Math.floor((tile * TILE_SIZE) / width) * TILE_SIZE,
|
|
TILE_SIZE,
|
|
TILE_SIZE,
|
|
col * TILE_SIZE,
|
|
row * TILE_SIZE,
|
|
TILE_SIZE,
|
|
TILE_SIZE
|
|
);
|
|
}
|
|
}
|
|
return (this._level = canvas);
|
|
}
|
|
|
|
render(ctx) {
|
|
if (!this.levelConfig || !this.selected) {
|
|
return;
|
|
}
|
|
ctx.drawImage(this.level, 0, 0);
|
|
}
|
|
}
|