这段代码主要是使用HTML5的Canvas元素来绘制一个星空效果。以下是对代码的解释和一些优化建议:
requestAnimationFrame
来创建一个连续的动画循环,在每一帧中更新星星的位置并重新绘制它们。这种星空效果常用于游戏背景、网站装饰或艺术展示等场合,为用户提供一个沉浸式的视觉体验。
requestAnimationFrame
的旧版浏览器,可以使用polyfill。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Starfield Animation</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="starfield"></canvas>
<script>
const canvas = document.getElementById('starfield');
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;
this.speed = Math.random() * 0.05;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.size / 2})`;
ctx.fill();
}
update() {
this.y -= this.speed;
if (this.y < 0) {
this.y = canvas.height;
}
}
}
const stars = Array.from({ length: 500 }, () => new Star());
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
stars.forEach(star => {
star.draw();
star.update();
});
requestAnimationFrame(animate);
}
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
这段代码创建了一个简单的星空动画,其中包含了星星的生成、更新和绘制逻辑。通过监听窗口大小的变化来调整Canvas的大小,确保动画在不同尺寸的屏幕上都能正常显示。
微搭低代码系列直播课
微搭低代码直播互动专栏
微搭低代码直播互动专栏
高校公开课
算力即生产力系列直播
Lowcode Talk
微搭低代码直播互动专栏
微搭低代码直播互动专栏
微搭低代码直播互动专栏
“中小企业”在线学堂
双11音视频系列直播
领取专属 10元无门槛券
手把手带您无忧上云