答案是使用canvas和requestAnimationFrame制作星空动画。首先创建canvas并获取上下文,生成包含位置、大小、透明度的星星数组,通过drawStars绘制每帧画面,利用animate函数结合requestAnimationFrame实现流畅循环,更新星星透明度模拟闪烁,并可调整位置创造飘动效果,核心在于清空、更新、重绘的动画流程控制。

用html5的Canvas制作星空背景动画,关键在于理解绘图上下文和动画循环机制。核心是通过canvas绘制星星,并用requestAnimationFrame实现流畅的循环动画。
1. 创建Canvas并设置基础环境
在HTML中添加<canvas>元素,并通过JavaScript获取绘图上下文:
<canvas id="starfield" width="800" height="600"></canvas> <script> const canvas = document.getElementById('starfield'); const ctx = canvas.getContext('2d'); const { width, height } = canvas; </script>
2. 生成随机星星数据
创建一个星星数组,每颗星包含位置、大小和亮度信息:
const stars = []; const starCount = 100; <p>for (let i = 0; i < starCount; i++) { stars.push({ x: Math.random() <em> width, y: Math.random() </em> height, radius: Math.random() * 1.5 + 0.5, opacity: Math.random() }); }</p>
3. 绘制星空
定义一个绘制函数,清空画布并重新绘制所有星星:
立即学习“前端免费学习笔记(深入)”;
function drawStars() { ctx.clearRect(0, 0, width, height); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, width, height); <p>stars.forEach(star => { ctx.beginPath(); ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2); ctx.fillStyle = <code>rgba(255, 255, 255, ${star.opacity})</code>; ctx.fill(); }); }</p>
4. 实现动画循环
使用requestAnimationFrame创建无限循环,可加入动态效果如星星闪烁或缓慢移动:
function animate() { // 更新星星透明度模拟闪烁 stars.forEach(star => { star.opacity += Math.random() * 0.05 - 0.025; if (star.opacity > 1) star.opacity = 1; if (star.opacity < 0) star.opacity = 0; }); <p>drawStars(); requestAnimationFrame(animate); }</p><p>// 启动动画 animate();</p>
这个方法的优点是性能好,requestAnimationFrame会自动匹配屏幕刷新率,避免浪费资源。如果想让星星有飘动感,可以在每次循环中轻微改变x或y值,并在超出边界时重置位置。
基本上就这些。掌握clearRect清空、状态更新、重绘三步流程,就能做出各种Canvas动画效果。


