add ball with click but remove oldest dot when limit reached
This commit is contained in:
@@ -25,6 +25,9 @@ export class DotBackground implements OnDestroy {
|
||||
private lastHeight = 0;
|
||||
private readonly RESIZE_THRESHOLD = 100; // ignore small height changes (browser chrome)
|
||||
|
||||
private ballSpawnId = 0;
|
||||
private ballSpawnNextColor = 0;
|
||||
|
||||
constructor(private ngZone: NgZone) {
|
||||
afterNextRender(() => {
|
||||
this.init();
|
||||
@@ -85,29 +88,48 @@ export class DotBackground implements OnDestroy {
|
||||
};
|
||||
|
||||
private onMouseClick = () => {
|
||||
if (this.dots.length < this.MAX_DOT_COUNT) {
|
||||
this.dots.push({
|
||||
x: this.mouse.x,
|
||||
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)],
|
||||
});
|
||||
}
|
||||
const dot = this.spawnDot();
|
||||
dot.x = this.mouse.x;
|
||||
dot.y = this.mouse.y;
|
||||
};
|
||||
|
||||
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() {
|
||||
const { width, height } = this.canvasRef.nativeElement;
|
||||
for (let i = 0; i < this.INIT_DOT_COUNT; i++) {
|
||||
this.dots.push({
|
||||
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],
|
||||
});
|
||||
this.spawnDot();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user