ujs/src/js/scene.js

82 lines
2.0 KiB
JavaScript

import { Pointer } from './pointer.js';
import { 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();
this.addObject(new uRect(50, 50, 100, 100, 'red'));
this.addObject(new uStrokeRect(150, 150, 40, 40, 'green', 'blue', 5));
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);
// draw item
this.#layers.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(`=> ${item.constructor.name}`);
}
});
}
#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);
}
addObject(object) {
this.#layers.push(object);
}
setScreenSize(w, h) {
this.#canvas.width = w;
this.#canvas.height = h;
}
}