feat(#8): improve performance
This commit is contained in:
parent
32dd2ad599
commit
07c64eadeb
4 changed files with 43 additions and 31 deletions
|
@ -1,4 +1,5 @@
|
|||
import { COLS, ROWS, TILE_SIZE } from "../constants.js";
|
||||
import { createCanvas } from "../utils.js";
|
||||
import { GameObject } from "./game-object.js";
|
||||
|
||||
export class Map extends GameObject {
|
||||
|
@ -7,22 +8,26 @@ export class Map extends GameObject {
|
|||
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 level = await fetch("/resources/" + this.name + ".json");
|
||||
this.level = await level.json();
|
||||
return true;
|
||||
const levelConfig = await fetch("/resources/" + this.name + ".json");
|
||||
this.levelConfig = await levelConfig.json();
|
||||
}
|
||||
|
||||
render(ctx) {
|
||||
if (!this.level) {
|
||||
return;
|
||||
get level() {
|
||||
if (this._level) {
|
||||
return this._level;
|
||||
}
|
||||
const levelImage = this.image;
|
||||
const level = 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;
|
||||
|
||||
|
@ -30,9 +35,9 @@ export class Map extends GameObject {
|
|||
for (let col = 0; col < COLS; col++) {
|
||||
const tile = data[row * COLS + col] - 1;
|
||||
ctx.drawImage(
|
||||
levelImage,
|
||||
(tile * TILE_SIZE) % levelImage.width,
|
||||
Math.floor((tile * TILE_SIZE) / levelImage.width) * TILE_SIZE,
|
||||
image,
|
||||
(tile * TILE_SIZE) % width,
|
||||
Math.floor((tile * TILE_SIZE) / width) * TILE_SIZE,
|
||||
TILE_SIZE,
|
||||
TILE_SIZE,
|
||||
col * TILE_SIZE,
|
||||
|
@ -42,5 +47,13 @@ export class Map extends GameObject {
|
|||
);
|
||||
}
|
||||
}
|
||||
return (this._level = canvas);
|
||||
}
|
||||
|
||||
render(ctx) {
|
||||
if (!this.levelConfig || !this.selected) {
|
||||
return;
|
||||
}
|
||||
ctx.drawImage(this.level, 0, 0);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue