Skip to content

Commit

Permalink
feat(ParticleGenerator): Bulk particle addition
Browse files Browse the repository at this point in the history
Add more than one particle per RAF.
TODO: use an easing function instead.
  • Loading branch information
alampros committed Mar 8, 2019
1 parent 0dd1959 commit 3c9e108
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/Confetti.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface IConfettiOptions {
opacity: number
recycle: boolean
run: boolean
debug: boolean
confettiSource: IRect
}

Expand All @@ -29,6 +30,7 @@ export const confettiDefaults: Pick<IConfettiOptions, Exclude<keyof IConfettiOpt
'#FF5722', '#795548',
],
opacity: 1.0,
debug: false,
recycle: true,
run: true,
}
Expand Down
25 changes: 22 additions & 3 deletions src/ParticleGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,28 +44,47 @@ export default class ParticleGenerator implements IParticleGenerator {
animate = (): boolean => {
const {
canvas,
context,
particlesGenerated,
} = this
const {
run,
recycle,
numberOfPieces,
debug,
} = this.getOptions()
if(!run) {
return false
}

const nP = this.particles.length
const limit = recycle ? nP : particlesGenerated

// Initial population
if(limit < numberOfPieces) {
this.particles.push(this.getParticle())
this.particlesGenerated += 1
// Add more than one piece per loop, otherwise the number of pieces would
// be limitted by the RAF framerate
const numToAdd = Math.ceil((numberOfPieces - limit) / 20)
for(let i = 0; i < numToAdd; i++) {
this.particles.push(this.getParticle())
}
this.particlesGenerated += numToAdd
}
if(debug) {
// Draw debug text
context.font = '12px serif'
context.fillStyle = '#333'
context.fillText(`Particles: ${nP}`, 20, 20)
}

// Maintain the population
this.particles.forEach((p, i) => {
// Update each particle's position
p.update()
// Prune the off-canvas particles
if(p.y > canvas.height || p.y < -100 || p.x > canvas.width + 100 || p.x < -100) {
if(recycle && limit <= numberOfPieces) {
// a brand new particle replacing the dead one
// Replace the particle with a brand new one
this.particles[i] = this.getParticle()
} else {
this.removeParticleAt(i)
Expand Down
1 change: 1 addition & 0 deletions www/src/components/KnobbedConfetti.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default (props) => {
wind={wind / 500}
gravity={gravity / 100}
style={{ zIndex: -1 }}
debug
{...props}
/>
<nav className={styles.nav}>
Expand Down

0 comments on commit 3c9e108

Please sign in to comment.