要实现“飘动的小星星”特效,可以使用HTML5的Canvas元素结合JavaScript来绘制和动画小星星。以下是实现该特效的基础概念、优势、类型、应用场景以及具体的实现方法。
requestAnimationFrame
来实现流畅的动画效果。以下是一个简单的2D飘动小星星特效的实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>飘动的小星星</title>
<style>
body {
margin: 0;
overflow: hidden;
background: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="starCanvas"></canvas>
<script>
const canvas = document.getElementById('starCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Star {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 2 + 1;
this.speed = Math.random() * 0.5 + 0.5;
this.color = `rgba(255, 255, 255, ${Math.random()})`;
}
update() {
this.y -= this.speed;
if (this.y < 0) {
this.y = canvas.height;
this.x = Math.random() * canvas.width;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
const stars = [];
for (let i = 0; i < 100; i++) {
stars.push(new Star());
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
stars.forEach(star => {
star.update();
star.draw();
});
requestAnimationFrame(animate);
}
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
animate();
</script>
</body>
</html>
Star
类,用于生成星星的属性(位置、大小、速度、颜色)。requestAnimationFrame
实现动画循环。通过这种方式,你可以创建一个简单的飘动小星星特效,并根据需要进行调整和扩展。
领取专属 10元无门槛券
手把手带您无忧上云