要实现一个HTML和JavaScript的花瓣飘落特效,我们可以使用HTML5的Canvas元素来绘制和动画化花瓣。以下是一个简单的示例代码,它创建了一个花瓣飘落的动画效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>花瓣飘落特效</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="petalCanvas"></canvas>
<script>
const canvas = document.getElementById('petalCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Petal {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * -canvas.height;
this.size = Math.random() * 5 + 2;
this.speed = Math.random() * 1 + 0.5;
this.wind = (Math.random() - 0.5) * 2;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = 'pink';
ctx.fill();
}
update() {
this.y += this.speed;
this.x += this.wind;
if (this.y > canvas.height) {
this.y = Math.random() * -canvas.height;
this.x = Math.random() * canvas.width;
}
}
}
const petals = [];
for (let i = 0; i < 100; i++) {
petals.push(new Petal());
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
petals.forEach(petal => {
petal.draw();
petal.update();
});
requestAnimationFrame(animate);
}
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>这个示例提供了一个基本的框架,你可以根据需要进一步调整和优化特效。
没有搜到相关的文章