ujs/src/js/scene.js

101 lines
2.3 KiB
JavaScript

import { Pointer } from './pointer.js';
import { uLayer, uRect, uStrokeRect } from './objects.js';
export class Scene {
#canvas;
#context;
#layers;
constructor(canvas, context, width, height) {
this.#canvas = canvas;
this.#context = context;
this.#layers = Array();
let layer = new uLayer('Entry', [
new uRect(50, 50, 100, 100, 'red'),
new uStrokeRect(150, 150, 40, 40, 'green', 'blue', 5),
]);
this.addLayer(layer);
this.init(width, height);
}
init(width, height) {
this.setScreenSize(width, height);
}
#clearCanvas() {
this.#context.clearRect(0, 0, this.#canvas.width, this.#canvas.height);
}
run() {
// clear canvas
this.#clearCanvas();
this.#scene();
}
#scene() {
// fill canvas
this.#context.fillStyle = '#523c4e';
this.#context.fillRect(0, 0, this.#canvas.width, this.#canvas.height);
// draw border
this.#context.strokeStyle = '#8bd0ba';
this.#context.lineWidth = 1;
this.#context.strokeRect(5, 5, this.#canvas.width - 10, this.#canvas.height - 10);
// read layers & draw items
this.#layers.forEach((layer) => {
layer.objects().forEach((item) => {
switch (item.constructor.name) {
case 'uRect':
this.#drawRect(item.x, item.y, item.width, item.height, item.fillColor);
break;
case 'uStrokeRect':
this.#drawStrokeRect(
item.x,
item.y,
item.width,
item.height,
item.fillColor,
item.strokeColor,
item.strokeWidth
);
break;
default:
console.log(`⛔ Error display '${item.constructor.name}' object.`);
}
});
});
}
#drawRect(x, y, w, h, fillColor) {
this.#context.fillStyle = fillColor;
this.#context.fillRect(x, y, w, h);
}
#drawStrokeRect(x, y, w, h, fillColor, strokeWidth, strokeColor) {
this.#drawRect(x, y, w, h, fillColor);
this.#context.strokeWidth = strokeWidth;
this.#context.strokeStyle = strokeColor;
this.#context.strokeRect(x, y, w, h);
}
addLayer(layer) {
this.#layers.push(layer);
}
removeLayers() {
this.#layers = Array();
}
setScreenSize(w, h) {
this.#canvas.width = w;
this.#canvas.height = h;
}
}