<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas 爱心动画特效</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 爱心粒子数组
const particles = [];
const particleCount = 150;
// 颜色数组
const colors = [
'#ff3366', '#ff6699', '#ff99cc',
'#ff0066', '#ff33cc', '#ff66ff',
'#ff0033', '#ff3399', '#ff66cc'
];
// 爱心形状函数
function heartShape(t, scale) {
scale = scale || 10;
return {
x: 16 * Math.pow(Math.sin(t), 3) * scale,
y: -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)) * scale
};
}
// 粒子类
class Particle {
constructor() {
this.reset();
this.angle = Math.random() * Math.PI * 2;
this.speed = 0.1 + Math.random() * 0.3;
this.radius = 1 + Math.random() * 3;
this.color = colors[Math.floor(Math.random() * colors.length)];
this.alpha = 0.6 + Math.random() * 0.4;
this.targetScale = 0.1 + Math.random() * 0.5;
this.scale = 0;
}
reset() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.angle = Math.random() * Math.PI * 2;
this.time = Math.random() * Math.PI * 2;
this.speed = 0.1 + Math.random() * 0.3;
this.radius = 1 + Math.random() * 3;
this.color = colors[Math.floor(Math.random() * colors.length)];
this.alpha = 0.6 + Math.random() * 0.4;
this.targetScale = 0.1 + Math.random() * 0.5;
this.scale = 0;
}
update() {
this.time += 0.01;
this.angle += this.speed * 0.1;
// 计算爱心形状位置
const heartPos = heartShape(this.time, this.targetScale * 15);
// 粒子位置
this.x = canvas.width / 2 + heartPos.x + Math.cos(this.angle) * 10;
this.y = canvas.height / 2 + heartPos.y + Math.sin(this.angle) * 10;
// 缩放动画
if (this.scale < this.targetScale) {
this.scale += 0.005;
}
// 随机重置粒子
if (Math.random() < 0.001) {
this.reset();
}
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius * this.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
// 初始化粒子
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);
// 更新和绘制所有粒子
particles.forEach(particle => {
particle.update();
particle.draw();
});
requestAnimationFrame(animate);
}
// 开始动画
animate();
// 窗口大小改变时调整画布大小
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
Canvas 爱心动画特效
于 2025-05-19 16:27:37 首次发布
462

被折叠的 条评论
为什么被折叠?



