mydeate/js/main.js
Lentil Hoffman 7a9fb5ac0c
Refactor to classes
This pattern is a natural fit for the js module system in the browser.
This gets rid of globals. Instead, index.js creates an instance of Main,
which then instantiates each of the specialized classes.

We should probably do class inheritance for the setMain pattern. On the other hand it's currently only 3 lines of code, so we'd only be saving 1 LOC per class, while creating a new class, and it wouldn't really be simpler. If our classes take on more features, we can further refactor.
2026-07-01 14:15:43 -05:00

44 lines
1.1 KiB
JavaScript

import { Elements } from "./elements.js";
import { Pointer } from "./pointer.js";
import { Canvases } from "./canvases.js";
const pointer = new Pointer();
export class Main {
div = undefined; // Constructor finds this by id
// Child objects we create
canvases = new Canvases();
elements = new Elements();
pointer = new Pointer();
// Initialize variables for main loop
run = true;
currentTime;
constructor(mainDivId) {
this.div = document.getElementById(mainDivId);
this.canvases.setMain(this);
this.elements.setMain(this);
this.pointer.setMain(this);
}
start() {
this.canvases.initialize();
this.pointer.initialize();
requestAnimationFrame(() => this.loop());
}
loop(elapsedTime) {
if (this.run) {
this.currentTime = document.timeline.currentTime;
this.canvases.clear();
this.pointer.updateHistory({ decay: true });
this.pointer.drawHistory();
this.elements.renderAll();
}
requestAnimationFrame(() => this.loop());
}
addElement(params) {
return this.elements.add(params);
}
}