feat(#8): modularizing
This commit is contained in:
parent
f300fe1be7
commit
32dd2ad599
11 changed files with 271 additions and 94 deletions
50
modules/game-objects/canvas-resizer.js
Normal file
50
modules/game-objects/canvas-resizer.js
Normal file
|
@ -0,0 +1,50 @@
|
|||
import { GameObject } from "./game-object.js";
|
||||
|
||||
export class CanvasResizer extends GameObject {
|
||||
/**
|
||||
* Creates a new instance of `CanvasResizer` class.
|
||||
* @param {Object} config - The configuration options for the class.
|
||||
* @param {HTMLCanvasElement} config.canvas - The canvas element to resize.
|
||||
* @param {number} config.width - The native width.
|
||||
* @param {number} config.height - The native height.
|
||||
* @param {number} config.percentage - The percentage of the screen size to use for the canvas.
|
||||
*/
|
||||
constructor({ canvas, width, height, percentage }) {
|
||||
super();
|
||||
this.canvas = canvas;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.percentage = percentage;
|
||||
|
||||
this.canvas.width = this.width;
|
||||
this.canvas.height = this.height;
|
||||
}
|
||||
|
||||
load() {
|
||||
if (this.loaded) {
|
||||
return;
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
["load", "resize"].map((item) =>
|
||||
window.addEventListener(item, () => {
|
||||
this._resize();
|
||||
if (item === "load") {
|
||||
resolve();
|
||||
this.loaded = true;
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
_resize() {
|
||||
let canvasWidth = Math.floor(window.innerWidth * this.percentage);
|
||||
let canvasHeight = Math.floor(canvasWidth / (this.width / this.height));
|
||||
if (canvasHeight >= window.innerHeight * this.percentage) {
|
||||
canvasHeight = Math.floor(window.innerHeight * this.percentage);
|
||||
canvasWidth = Math.floor(canvasHeight / (this.height / this.width));
|
||||
}
|
||||
this.canvas.style.width = canvasWidth + "px";
|
||||
this.canvas.style.height = canvasHeight + "px";
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue