当然可以!下面是一个比《打扰一下,我是李峋》中更好看的 “爱心代码飘散效果”,使用纯 HTML + CSS + JavaScript 实现,具有以下特点:
- 粒子形状为爱心 ❤️
- 动态随机飘落
- 色彩丰富渐变
- 支持移动端和 PC 浏览器
🌟 最终效果描述
页面中不断飘落五彩的爱心,带有透明度渐变和旋转效果,视觉上类似“下雪+爱心”的浪漫结合。
📦 源码实现
✅ HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>飘落爱心效果</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="loveCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
✅ CSS(style.css)
body, html {
margin: 0;
padding: 0;
overflow: hidden;
background: #000; /* 深色背景下更浪漫 */
}
canvas {
display: block;
}
✅ JavaScript(script.js)
const canvas = document.getElementById("loveCanvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.onresize = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
const hearts = [];
function createHeart() {
return {
x: Math.random() * canvas.width,
y: -20,
size: Math.random() * 20 + 10,
speed: Math.random() * 1 + 0.5,
angle: Math.random() * 2 * Math.PI,
rotateSpeed: Math.random() * 0.02 - 0.01,
color: `hsl(${Math.random() * 360}, 100%, 70%)`,
opacity: Math.random() * 0.5 + 0.3
};
}
function drawHeart(x, y, size, angle, color, opacity) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.scale(size / 20, size / 20);
ctx.beginPath();
ctx.moveTo(0, -10);
ctx.bezierCurveTo(-12, -18, -15, 0, 0, 10);
ctx.bezierCurveTo(15, 0, 12, -18, 0, -10);
ctx.closePath();
ctx.fillStyle = color;
ctx.globalAlpha = opacity;
ctx.fill();
ctx.restore();
ctx.globalAlpha = 1;
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (hearts.length < 150) {
hearts.push(createHeart());
}
for (let i = 0; i < hearts.length; i++) {
const h = hearts[i];
h.y += h.speed;
h.angle += h.rotateSpeed;
drawHeart(h.x, h.y, h.size, h.angle, h.color, h.opacity);
if (h.y > canvas.height + 20) {
hearts.splice(i, 1);
i--;
}
}
requestAnimationFrame(animate);
}
animate();
💡 效果优化建议
- 可配合背景音乐实现浪漫告白页
- 可添加点击生成更多爱心效果
- 如果用于网页背景,可降低透明度与数量,减少性能压力
🧪 在线预览建议
你可以将这三段代码保存在本地 index.html
, style.css
, script.js
中,然后直接双击打开 index.html
即可看到浪漫爱心飘散。
或者,复制粘贴到如下网站中体验:
发表回复