vue实现动态星空效果
Vue实现动态星空效果
动态星空效果可以通过Vue结合Canvas或CSS动画实现。以下是两种常见方法:
使用Canvas绘制星空
-
创建Vue组件 在Vue项目中创建一个组件(如
StarSky.vue),使用Canvas绘制星空:<template> <canvas ref="canvas" class="star-canvas"></canvas> </template> <script> export default { mounted() { this.initCanvas(); }, methods: { initCanvas() { const canvas = this.$refs.canvas; const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const stars = []; const starCount = 200; for (let i = 0; i < starCount; i++) { stars.push({ x: Math.random() * canvas.width, y: Math.random() * canvas.height, radius: Math.random() * 1.5, speed: Math.random() * 0.5 }); } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'white'; stars.forEach(star => { star.y += star.speed; if (star.y > canvas.height) { star.y = 0; star.x = Math.random() * canvas.width; } ctx.beginPath(); ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2); ctx.fill(); }); requestAnimationFrame(animate); } animate(); } } }; </script> <style> .star-canvas { position: fixed; top: 0; left: 0; z-index: -1; } </style> -
调整参数

- 修改
starCount可调整星星数量 - 调整
radius和speed可改变星星大小和移动速度
- 修改
使用CSS动画实现
-
创建星星元素 通过Vue动态生成多个星星元素并应用CSS动画:
<template> <div class="star-container"> <div v-for="(star, index) in stars" :key="index" class="star" :style="{ left: star.x + 'px', top: star.y + 'px', width: star.size + 'px', height: star.size + 'px', animationDuration: star.duration + 's', animationDelay: star.delay + 's' }" ></div> </div> </template> <script> export default { data() { return { stars: [] }; }, created() { const starCount = 100; for (let i = 0; i < starCount; i++) { this.stars.push({ x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight, size: Math.random() * 3, duration: 2 + Math.random() * 10, delay: Math.random() * 5 }); } } }; </script> <style> .star-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; overflow: hidden; } .star { position: absolute; background-color: white; border-radius: 50%; animation: twinkle linear infinite; } @keyframes twinkle { 0% { opacity: 0.2; } 50% { opacity: 1; } 100% { opacity: 0.2; } } </style> -
优化性能

- 对于大量星星,使用CSS
transform属性代替top/left定位 - 考虑使用
will-change: transform提升动画性能
- 对于大量星星,使用CSS
进阶效果
-
添加流星效果 在Canvas实现中添加流星动画:
// 在Canvas实现中添加 function createShootingStar() { return { x: Math.random() * canvas.width, y: 0, length: 5 + Math.random() * 10, speed: 3 + Math.random() * 5, angle: Math.PI / 4 }; } // 在animate函数中添加流星绘制逻辑 -
响应式调整 监听窗口大小变化,重新计算Canvas尺寸和星星位置:
mounted() { this.initCanvas(); window.addEventListener('resize', this.handleResize); }, beforeDestroy() { window.removeEventListener('resize', this.handleResize); }, methods: { handleResize() { // 重新初始化Canvas } }
选择Canvas方法适合更复杂的动态效果,CSS方法实现更简单且对性能影响较小。根据项目需求选择合适方案。






