js实现漩涡

实现漩涡效果的方法
使用JavaScript和Canvas可以轻松实现漩涡效果。以下是两种常见的实现方式:
使用粒子系统创建漩涡
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = [];
const particleCount = 500;
class Particle {
constructor() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
update() {
const dx = this.x - canvas.width / 2;
const dy = this.y - canvas.height / 2;
const distance = Math.sqrt(dx * dx + dy * dy);
const forceDirectionX = dx / distance;
const forceDirectionY = dy / distance;
const force = (canvas.width / 2 - distance) / canvas.width * 2;
this.speedX += forceDirectionX * force;
this.speedY += forceDirectionY * force;
this.x += this.speedX;
this.y += this.speedY;
this.size -= 0.1;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
function init() {
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
}
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
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].size <= 0.3) {
particles.splice(i, 1);
particles.push(new Particle());
}
}
requestAnimationFrame(animate);
}
init();
animate();
使用数学公式绘制漩涡
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawSwirl() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const maxRadius = Math.min(canvas.width, canvas.height) * 0.4;
for (let angle = 0; angle < Math.PI * 16; angle += 0.01) {
const radius = angle * 10;
if (radius > maxRadius) break;
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
const hue = (angle * 180 / Math.PI) % 360;
ctx.fillStyle = `hsl(${hue}, 100%, 50%)`;
ctx.fillRect(x, y, 2, 2);
}
requestAnimationFrame(drawSwirl);
}
drawSwirl();
优化漩涡效果
- 添加交互性可以让漩涡对鼠标移动做出反应
- 调整颜色渐变可以创建更生动的视觉效果
- 控制粒子生命周期可以影响漩涡的密度和流动感
- 添加模糊效果可以增强漩涡的柔和度
性能考虑
- 对于大量粒子,考虑使用WebGL代替Canvas 2D
- 限制动画帧率可以降低CPU/GPU使用率
- 使用requestAnimationFrame确保平滑动画
- 避免在动画循环中创建新对象,尽量复用现有对象







