js实现喷泉
实现喷泉效果的JavaScript方法
使用HTML5的Canvas元素和JavaScript可以轻松实现喷泉效果。以下是实现步骤:
创建Canvas元素并设置基本样式:
<canvas id="fountainCanvas" width="800" height="600"></canvas>
<style>
#fountainCanvas {
background-color: #000;
display: block;
margin: 0 auto;
}
</style>
初始化粒子系统:
const canvas = document.getElementById('fountainCanvas');
const ctx = canvas.getContext('2d');
const particles = [];
const particleCount = 100;
const gravity = 0.1;
创建粒子类:
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * -5 - 5;
this.color = `hsl(${Math.random() * 60 + 180}, 100%, 50%)`;
this.life = 100;
}
update() {
this.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.life--;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
动画循环和粒子生成:
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
if (particles[i].life <= 0 || particles[i].y > canvas.height) {
particles.splice(i, 1);
i--;
}
}
while (particles.length < particleCount) {
particles.push(new Particle(canvas.width / 2, canvas.height - 20));
}
requestAnimationFrame(animate);
}
animate();
增强喷泉效果的技巧
调整粒子颜色可以创建更生动的效果:
// 在Particle类构造函数中修改颜色生成
this.color = `hsl(${Math.random() * 60 + 180}, 100%, ${Math.random() * 30 + 50}%)`;
添加透明度变化使粒子逐渐消失:
// 在draw方法中添加透明度
ctx.globalAlpha = this.life / 100;
实现多喷泉源效果:
// 修改粒子生成逻辑
const sources = [
{x: canvas.width/3, y: canvas.height-20},
{x: canvas.width/2, y: canvas.height-20},
{x: canvas.width*2/3, y: canvas.height-20}
];
while (particles.length < particleCount) {
const source = sources[Math.floor(Math.random() * sources.length)];
particles.push(new Particle(source.x, source.y));
}
性能优化建议
对于大量粒子,可以考虑使用对象池技术:
const particlePool = [];
function getParticle(x, y) {
if (particlePool.length > 0) {
const p = particlePool.pop();
p.x = x;
p.y = y;
p.life = 100;
return p;
}
return new Particle(x, y);
}
// 在移除粒子时
if (particles[i].life <= 0 || particles[i].y > canvas.height) {
particlePool.push(particles[i]);
particles.splice(i, 1);
i--;
}
使用requestAnimationFrame的timestamp参数实现时间控制:
let lastTime = 0;
function animate(timestamp) {
if (!lastTime) lastTime = timestamp;
const deltaTime = timestamp - lastTime;
lastTime = timestamp;
// 使用deltaTime调整动画速度
// ...
requestAnimationFrame(animate);
}






