I'm trying to figure out how to stop this particle system after 30 seconds. Is there a way for it to stop cold, so the particles freeze where they are? And is there alternate way for the particles to die out, so that any particle that has already started completes it's path off screen?
I'm not an advanced coder and found this system online, I appreciate any help. Thanks.
var INTENSITY = 200;
(function(ns) {
ns = ns || window;
function ParticleSystem(ctx, width, height, intensity) {
this.particles = [];
intensity = intensity;
this.addParticle = function() {
this.particles.push(new Snow(ctx, width));
}
while (intensity--) {
this.addParticle();
}
this.render = function() {
ctx.save();
ctx.clearRect(0,0,width,height);
for (var i = 0, particle; particle = this.particles[i]; i++) {
particle.render();
}
ctx.restore();
}
this.update = function() {
for (var i = 0, particle; particle = this.particles[i]; i++) {
particle.x += particle.vx;
particle.y += particle.vy + 1;
if (particle.y > height - 1) {
particle.vx = 0;
particle.vy = 0;
particle.y = height;
if (particle.killAt && particle.killAt < +new Date) this.particles.splice(i--, 1);
else if (!particle.killAt) {
particle.killAt = +new Date + 5000;
this.addParticle();
}
}
}
}
}
function Snow(ctx, width) {
this.vx = ((Math.random() - 0.5) * 5);
this.vy = (Math.random() * 4) + 0.25;
this.x = Math.floor((Math.random() * width));
this.y = -Math.random() * 30;
this.alpha = (Math.random() * 0.99) + 0.15;
this.radius = Math.random() * 3;
this.color = 'rgba(255,255,255,1)';
this.render = function() {
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
}
ns.precCanvas = function() {
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var width = myCanvas.width = 300;
var height = myCanvas.height = 610;
var particleSystem = new ParticleSystem(ctx, width, height, INTENSITY);
(function draw() {
requestAnimationFrame(draw);
particleSystem.update();
particleSystem.render();
})();
}
})(window);
precCanvas();
You'll need to store the animationId
returned by requestAnimationFrame
and then at a later time stop the animation. Replace your precCanvas
function with this:
ns.precCanvas = function() {
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var width = myCanvas.width = 300;
var height = myCanvas.height = 610;
var particleSystem = new ParticleSystem(ctx, width, height, INTENSITY);
var animationId;
function draw() {
animationId = requestAnimationFrame(draw);
particleSystem.update();
particleSystem.render();
}
function stop() {
window.cancelAnimationFrame(animationId);
}
setTimeout(stop, 30 * 1000);
draw();
}
A working fiddle here.