我试图弄清楚如何在30秒后停止这个粒子系统。有没有办法阻止它,所以颗粒会冻结在哪里?是否存在颗粒消失的替代方式,以便任何已经开始的粒子完成它的离开屏幕的路径?
我不是高级程序员并且在线发现此系统,我感谢任何帮助。感谢。
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();
答案 0 :(得分:0)
您需要存储animationId
返回的requestAnimationFrame
,然后稍后停止动画。将precCanvas
函数替换为:
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();
}
工作小提琴here。