|
| 1 | +var Particle = function(options) { |
| 2 | + this.alpha = options.alpha || 1; |
| 3 | + this.color = this.hexToRgb(options.color); |
| 4 | + this.radius = options.radius || 5; |
| 5 | + this.speed = options.speed || 10; |
| 6 | + this.x = options.x || 0; |
| 7 | + this.y = options.y || 0; |
| 8 | + this.vx = (Math.random() * this.speed) - (this.speed / 2); |
| 9 | + this.vy = (Math.random() * this.speed) - (this.speed / 2); |
| 10 | +}; |
| 11 | + |
| 12 | +Particle.prototype.hexToRgb = function(hex) { |
| 13 | + let [, red, green, blue] = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); |
| 14 | + return { r: parseInt(red, 16), g: parseInt(green, 16), b: parseInt(blue, 16) }; |
| 15 | +}; |
| 16 | + |
| 17 | +Particle.prototype.draw = function(ctx) { |
| 18 | + this.x += this.vx; |
| 19 | + this.y += this.vy; |
| 20 | + this.alpha -= 0.01; |
| 21 | + ctx.beginPath(); |
| 22 | + ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); |
| 23 | + ctx.fillStyle = `rgba(${this.color.r}, ${this.color.g}, ${this.color.b}, ${this.alpha}`; |
| 24 | + ctx.fill(); |
| 25 | +}; |
| 26 | + |
| 27 | +Particle.startRendering = function(context, particles) { |
| 28 | + |
| 29 | + context.clearRect(0, 0, context.canvas.width, context.canvas.height); |
| 30 | + |
| 31 | + for(let i = 0; i < particles.length; i++) { |
| 32 | + |
| 33 | + if ( |
| 34 | + particles[i].x < 0 || particles[i].x > context.canvas.width || |
| 35 | + particles[i].y < 0 || particles[i].y > context.canvas.height || |
| 36 | + particles[i].alpha < 0 |
| 37 | + ) { |
| 38 | + particles.splice(i, 1); |
| 39 | + } else { |
| 40 | + particles[i].draw(context); |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + requestAnimationFrame(() => { |
| 46 | + this.startRendering(context, particles); |
| 47 | + }); |
| 48 | + |
| 49 | +}; |
0 commit comments