请你用html5,帮我写一个动态爱心背景的页面
时间: 2024-03-05 19:48:03 浏览: 47
HTML5实现动态爱心特效
5星 · 资源好评率100%
好的,以下是一个简单的HTML5动态爱心背景页面的代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态爱心背景</title>
<style>
body {
background-color: black;
text-align: center;
color: white;
font-size: 36px;
font-weight: bold;
font-family: Arial, sans-serif;
}
canvas {
position: absolute;
z-index: -1;
left: 0;
top: 0;
}
</style>
</head>
<body>
<h1>我喜欢你,你愿意做我的女朋友吗?</h1>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
// 创建爱心
function createHeart() {
var heart = {};
heart.x = Math.random() * canvas.width;
heart.y = Math.random() * canvas.height;
heart.color = getRandomColor();
heart.size = Math.random() * 30 + 20;
heart.speed = Math.random() * 5 + 1;
hearts.push(heart);
}
// 获取随机颜色
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// 绘制爱心
function drawHeart(heart) {
ctx.beginPath();
ctx.moveTo(heart.x, heart.y);
ctx.lineTo(heart.x + heart.size / 2, heart.y - heart.size);
ctx.bezierCurveTo(heart.x + heart.size / 2, heart.y - heart.size * 2, heart.x - heart.size / 2, heart.y - heart.size * 2, heart.x - heart.size / 2, heart.y - heart.size);
ctx.closePath();
ctx.fillStyle = heart.color;
ctx.fill();
heart.y += heart.speed;
if (heart.y > canvas.height + heart.size) {
hearts.splice(hearts.indexOf(heart), 1);
}
}
// 动画循环
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.05) {
createHeart();
}
for (var i = 0; i < hearts.length; i++) {
drawHeart(hearts[i]);
}
requestAnimationFrame(loop);
}
var hearts = [];
loop();
</script>
</body>
</html>
```
这个页面会在黑色背景上生成多个随机颜色的爱心,同时上面有一句简单的表白。当用户打开这个页面时,会看到动态的爱心背景效果,非常浪漫。
阅读全文