Vue組件-霓虹燈:技術解析與實現
本文將詳細解析如何使用Vue 3實現一個動態炫彩霓虹燈效果。
預覽
概述
此Vue組件創建了一個由7個同心圓環組成的霓虹燈效果,每個圓環具有彩虹中的一種顏色(紅、橙、黃、綠、藍、靛、紫)。這些圓環的顏色會動態輪轉變化,產生向外流動的視覺效果。
實現代碼
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'const colors = ['#ff0000', // 紅色'#ff7f00', // 橙色'#ffff00', // 黃色'#00ff00', // 綠色'#0000ff', // 藍色'#4b0082', // 靛藍'#9400d3' // 紫色
]const currentColors = ref([...colors])
const animationInterval = ref(null)function rotateColors() {// 顏色輪轉currentColors.value.push(currentColors.value.shift())
}function start() {if (!animationInterval.value) {animationInterval.value = setInterval(rotateColors, 100) // 變化間隔}
}function stop() {if (animationInterval.value) {clearInterval(animationInterval.value)animationInterval.value = null}
}onMounted(() => {start() // 默認自動開始
})onBeforeUnmount(() => {stop() // 組件卸載時清除定時器
})// 暴露方法給父組件
defineExpose({start,stop
})
</script><template><div class="neon-container"><divv-for="(color, index) in currentColors":key="index"class="neon-ring":style="{'--ring-color': color,'--ring-size': `${(7 - index) * 50}px`,'--inner-size': `${(6 - index) * 50}px`}"></div></div>
</template><style scoped>
.neon-container {position: relative;width: 400px;height: 400px;display: flex;justify-content: center;align-items: center;
}.neon-ring {position: absolute;border-radius: 50%;width: var(--ring-size);height: var(--ring-size);background: var(--ring-color);box-shadow: 0 0 10px var(--ring-color),0 0 20px var(--ring-color);transition: background 0.3s ease, box-shadow 0.3s ease;
}.neon-ring::after {content: '';position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width: var(--inner-size);height: var(--inner-size);background: #000;border-radius: 50%;
}
</style>
技術解析
1. ref
currentColors
存儲當前顏色數組animationInterval
存儲定時器引用
2. 顏色算法
function rotateColors() {currentColors.value.push(currentColors.value.shift())
}
這個簡單的算法實現了顏色循環效果:
shift()
移除數組第一個元素push()
將移除的元素添加到數組末尾- 結果是顏色數組不斷"輪轉"
3. 定時器控制
function start() {if (!animationInterval.value) {animationInterval.value = setInterval(rotateColors, 100)}
}function stop() {if (animationInterval.value) {clearInterval(animationInterval.value)animationInterval.value = null}
}
- 使用
setInterval
每100毫秒調用一次rotateColors
- 提供
start
和stop
方法控制動畫,并通過defineExpose
暴露給父組件
4. CSS實現霓虹效果
.neon-ring {/* ... */box-shadow: 0 0 10px var(--ring-color),0 0 20px var(--ring-color);transition: background 0.3s ease, box-shadow 0.3s ease;
}
霓虹效果主要通過CSS實現:
- box-shadow:創建發光效果,兩層陰影增強立體感
- transition:使顏色變化更平滑
- 偽元素:
:after
創建黑色內圓,形成圓環效果
5. 動態樣式綁定
<divv-for="(color, index) in currentColors":key="index"class="neon-ring":style="{'--ring-color': color,'--ring-size': `${(7 - index) * 50}px`,'--inner-size': `${(6 - index) * 50}px`}"
></div>
- v-for:循環渲染7個圓環
- 動態樣式:通過
:style
綁定CSS變量--ring-color
:當前顏色--ring-size
:圓環大小,從大到小(350px到50px)--inner-size
:內圓大小,形成圓環厚度