ujs/src/js/scene.js

107 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-02-16 00:04:40 +03:00
import { Pointer } from './pointer.js';
export class Scene {
2023-04-06 15:03:09 +03:00
#canvas;
#context;
2023-04-06 16:52:57 +03:00
#layers;
2023-04-06 15:03:09 +03:00
constructor(canvas, context, width, height) {
this.#canvas = canvas;
this.#context = context;
2023-04-06 16:52:57 +03:00
this.#layers = Array();
2023-04-06 14:44:41 +03:00
this.setScreenSize(width, height);
2023-02-16 00:04:40 +03:00
}
run() {
2023-04-23 17:01:17 +03:00
this.#update();
this.#draw();
2023-04-06 15:03:09 +03:00
}
2023-04-06 14:52:58 +03:00
2023-04-23 17:01:17 +03:00
#update() {
// read layers & draw items
this.#layers.forEach((layer) => {
layer.objects().forEach((item) => {
if (typeof item.ticker == 'function') {
item.ticker();
}
});
});
}
#draw() {
2023-04-06 17:15:27 +03:00
// read layers & draw items
this.#layers.forEach((layer) => {
layer.objects().forEach((item) => {
switch (item.constructor.name) {
2023-04-06 18:46:01 +03:00
case 'Rect':
2023-04-06 17:15:27 +03:00
this.#drawRect(item.x, item.y, item.width, item.height, item.fillColor);
break;
2023-04-06 18:46:01 +03:00
case 'StrokeRect':
2023-04-06 18:03:40 +03:00
this.#drawStrokeRect(
item.x,
item.y,
item.width,
item.height,
item.fillColor,
item.strokeColor,
item.strokeWidth
);
2023-04-06 17:15:27 +03:00
break;
default:
console.log(`⛔ Error display '${item.constructor.name}' object.`);
}
});
2023-04-06 16:52:57 +03:00
});
}
#drawRect(x, y, w, h, fillColor) {
this.#context.fillStyle = fillColor;
this.#context.fillRect(x, y, w, h);
}
2023-04-06 18:46:01 +03:00
#drawStrokeRect(x, y, w, h, fillColor, strokeColor, strokeWidth) {
2023-04-06 17:15:27 +03:00
this.#drawRect(x, y, w, h, fillColor);
2023-04-06 16:52:57 +03:00
2023-04-06 18:46:01 +03:00
this.#context.lineWidth = strokeWidth;
2023-04-06 17:15:27 +03:00
this.#context.strokeStyle = strokeColor;
this.#context.strokeRect(x, y, w, h);
2023-04-06 16:52:57 +03:00
}
2023-04-06 17:15:27 +03:00
addLayer(layer) {
this.#layers.push(layer);
}
removeLayers() {
this.#layers = Array();
2023-02-16 00:04:40 +03:00
}
2023-04-06 14:44:41 +03:00
setScreenSize(w, h) {
2023-04-06 15:03:09 +03:00
this.#canvas.width = w;
this.#canvas.height = h;
2023-02-16 00:04:40 +03:00
}
}
2023-04-06 18:46:01 +03:00
export class SceneLayer {
#objects;
constructor(name, objects = Array()) {
// TODO: check types
this.#objects = Array();
objects.forEach((object) => {
this.#objects.push(object);
});
}
add(object) {
this.#objects.push(object);
}
objects() {
return this.#objects;
}
}