-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParticle.js
44 lines (36 loc) · 1.51 KB
/
Particle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import * as vectors from './utils/vectors.js';
export default class Particle {
constructor({x, y, speed=150, minLifetime = 0.15, maxLifetime = 0.5, r=255, g=255, b=255, maxAlpha=0.5, size=5}){
this.position = {x, y};
this.lifetime = minLifetime + Math.random() * (maxLifetime - minLifetime);
this.age = 0;
this.alive = true;
this.color = {r,g,b};
this.maxAlpha = maxAlpha;
this.size = size
const angle = Math.random() * 2 * Math.PI;
const rand = Math.random();
const length = (1 - rand * rand) * speed;
this.movement = {
x: Math.cos(angle) * length,
y: Math.sin(angle) * length
}
};
update(dt){
vectors.addInPlace(this.position, vectors.scale(this.movement, dt));
vectors.scaleInPlace(this.movement, Math.max(0, 1 - 5*dt));
this.age += dt;
this.alive = this.age < this.lifetime;
};
draw(ctx){
ctx.save();
ctx.translate(this.position.x, this.position.y);
const alpha = this.maxAlpha * Math.max(0, 1 - this.age/this.lifetime);
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, this.size);
gradient.addColorStop(0, `rgba(${this.color.r}, ${this.color.g}, ${this.color.b}, ${alpha})`);
gradient.addColorStop(1, `rgba(${this.color.r}, ${this.color.g}, ${this.color.b}, 0)`);
ctx.fillStyle = gradient;
ctx.fillRect(-this.size, -this.size, 2*this.size, 2*this.size);
ctx.restore();
};
}