请用canvas写一个关于520浪漫表白的代码
<!DOCTYPE html>
<html>
<head>
<title>520浪漫表白</title>
<style>
body { margin: 0; overflow: hidden; background-color: #000; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const heartSize = 20;
const hearts = [];
function createHeart(x, y, vx, vy, color) {
return { x, y, vx, vy, color };
}
function drawHeart(heart) {
ctx.beginPath();
ctx.fillStyle = heart.color;
ctx.moveTo(heart.x, heart.y);
ctx.bezierCurveTo(heart.x - heartSize / 2, heart.y - heartSize, heart.x - heartSize, heart.y - heartSize / 2, heart.x, heart.y - heartSize * 1.5);
ctx.bezierCurveTo(heart.x + heartSize, heart.y - heartSize / 2, heart.x + heartSize / 2, heart.y - heartSize, heart.x, heart.y);
ctx.fill();
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.1) { // 控制心形出现的频率
const x = Math.random() * canvas.width;
const y = canvas.height;
const vx = (Math.random() - 0.5) * 2; // x 方向速度
const vy = -Math.random() * 5 - 2; // y 方向速度
const color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`; // 随机颜色
//const color = `#FF69B4`; //粉色
hearts.push(createHeart(x, y, vx, vy, color));
}
for (let i = 0; i < hearts.length; i++) {
const heart = hearts[i];
heart.x += heart.vx;
heart.y += heart.vy;
drawHeart(heart);
if (heart.y < -heartSize) { // 心形飘出屏幕顶部后移除
hearts.splice(i, 1);
i--; // 调整索引,避免跳过元素
}
}
}
// 添加文字
ctx.font = "30px Arial";
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.fillText("520 我爱你", canvas.width / 2, canvas.height / 2);
animate();
// 调整 canvas 大小以适应窗口变化
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 这里需要重新绘制文字,因为 canvas 清空了
ctx.font = "30px Arial";
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.fillText("520 我爱你", canvas.width / 2, canvas.height / 2);
});
</script>
</body>
</html>
这段代码会在黑色背景上不断向上飘爱心,并带有“520 我爱你”的文字。爱心颜色随机,大小和出现频率可以调整。主要改进包括:
- 爱心形状更优美: 使用贝塞尔曲线绘制更漂亮的爱心。
- 颜色随机: 爱心颜色随机变化,更活泼。
- 移除飘出屏幕的爱心: 优化性能,避免无限累积爱心对象。
- 自适应窗口大小: canvas 大小会随着窗口变化而调整,保持良好的显示效果。
- 文字始终居中: 即使窗口大小改变,文字也始终保持在屏幕中央。
使用方法:将代码保存为 HTML 文件,然后用浏览器打开即可。
可以根据自己的喜好修改文字内容、颜色、爱心大小、出现频率等参数,打造更个性化的表白效果。例如,可以将`const color =
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步