Skip to content

Commit 3c9e108

Browse files
committed
feat(ParticleGenerator): Bulk particle addition
Add more than one particle per RAF. TODO: use an easing function instead.
1 parent 0dd1959 commit 3c9e108

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

src/Confetti.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export interface IConfettiOptions {
1212
opacity: number
1313
recycle: boolean
1414
run: boolean
15+
debug: boolean
1516
confettiSource: IRect
1617
}
1718

@@ -29,6 +30,7 @@ export const confettiDefaults: Pick<IConfettiOptions, Exclude<keyof IConfettiOpt
2930
'#FF5722', '#795548',
3031
],
3132
opacity: 1.0,
33+
debug: false,
3234
recycle: true,
3335
run: true,
3436
}

src/ParticleGenerator.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,28 +44,47 @@ export default class ParticleGenerator implements IParticleGenerator {
4444
animate = (): boolean => {
4545
const {
4646
canvas,
47+
context,
4748
particlesGenerated,
4849
} = this
4950
const {
5051
run,
5152
recycle,
5253
numberOfPieces,
54+
debug,
5355
} = this.getOptions()
5456
if(!run) {
5557
return false
5658
}
59+
5760
const nP = this.particles.length
5861
const limit = recycle ? nP : particlesGenerated
62+
63+
// Initial population
5964
if(limit < numberOfPieces) {
60-
this.particles.push(this.getParticle())
61-
this.particlesGenerated += 1
65+
// Add more than one piece per loop, otherwise the number of pieces would
66+
// be limitted by the RAF framerate
67+
const numToAdd = Math.ceil((numberOfPieces - limit) / 20)
68+
for(let i = 0; i < numToAdd; i++) {
69+
this.particles.push(this.getParticle())
70+
}
71+
this.particlesGenerated += numToAdd
72+
}
73+
if(debug) {
74+
// Draw debug text
75+
context.font = '12px serif'
76+
context.fillStyle = '#333'
77+
context.fillText(`Particles: ${nP}`, 20, 20)
6278
}
6379

80+
// Maintain the population
6481
this.particles.forEach((p, i) => {
82+
// Update each particle's position
6583
p.update()
84+
// Prune the off-canvas particles
6685
if(p.y > canvas.height || p.y < -100 || p.x > canvas.width + 100 || p.x < -100) {
6786
if(recycle && limit <= numberOfPieces) {
68-
// a brand new particle replacing the dead one
87+
// Replace the particle with a brand new one
6988
this.particles[i] = this.getParticle()
7089
} else {
7190
this.removeParticleAt(i)

www/src/components/KnobbedConfetti.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export default (props) => {
2323
wind={wind / 500}
2424
gravity={gravity / 100}
2525
style={{ zIndex: -1 }}
26+
debug
2627
{...props}
2728
/>
2829
<nav className={styles.nav}>

0 commit comments

Comments
 (0)