add ball with click but remove oldest dot when limit reached

This commit is contained in:
2026-01-21 18:46:12 +01:00
parent 47920509d3
commit fb917d56e6

View File

@@ -25,6 +25,9 @@ export class DotBackground implements OnDestroy {
private lastHeight = 0; private lastHeight = 0;
private readonly RESIZE_THRESHOLD = 100; // ignore small height changes (browser chrome) private readonly RESIZE_THRESHOLD = 100; // ignore small height changes (browser chrome)
private ballSpawnId = 0;
private ballSpawnNextColor = 0;
constructor(private ngZone: NgZone) { constructor(private ngZone: NgZone) {
afterNextRender(() => { afterNextRender(() => {
this.init(); this.init();
@@ -85,29 +88,48 @@ export class DotBackground implements OnDestroy {
}; };
private onMouseClick = () => { private onMouseClick = () => {
if (this.dots.length < this.MAX_DOT_COUNT) { const dot = this.spawnDot();
this.dots.push({ dot.x = this.mouse.x;
x: this.mouse.x, dot.y = this.mouse.y;
y: this.mouse.y,
vx: (Math.random() - 0.5) * 0.5,
vy: (Math.random() - 0.5) * 0.5,
radius: Math.random() * 60 + 40,
color: this.COLORS[Math.floor(Math.random() * this.COLORS.length)],
});
}
}; };
private spawnDot(): Dot {
const dotId = this.ballSpawnId++;
let dot;
if (this.ballSpawnId < this.MAX_DOT_COUNT) {
dot = {
x: 0,
y: 0,
vx: 0,
vy: 0,
radius: 1,
color: "#000000",
};
this.dots.push(dot);
} else {
dot = this.dots[dotId % this.MAX_DOT_COUNT];
}
this.populateDot(dot);
return dot;
}
private populateDot(dot: Dot) {
const {width, height} = this.canvasRef.nativeElement;
dot.x = Math.random() * width;
dot.y = Math.random() * height;
dot.vx = (Math.random() - 0.5) * 0.5;
dot.vy = (Math.random() - 0.5) * 0.5;
dot.radius = Math.random() * 60 + 40;
dot.color = this.COLORS[this.ballSpawnNextColor++ % this.COLORS.length];
}
private initDots() { private initDots() {
const { width, height } = this.canvasRef.nativeElement;
for (let i = 0; i < this.INIT_DOT_COUNT; i++) { for (let i = 0; i < this.INIT_DOT_COUNT; i++) {
this.dots.push({ this.spawnDot();
x: Math.random() * width,
y: Math.random() * height,
vx: (Math.random() - 0.5) * 0.5,
vy: (Math.random() - 0.5) * 0.5,
radius: Math.random() * 60 + 40,
color: this.COLORS[i % this.COLORS.length],
});
} }
} }