vue实现能量球

Vue 实现能量球效果
能量球效果通常指动态的、可交互的球形 UI 元素,常用于数据可视化或游戏界面。以下是基于 Vue 3 的实现方法:
使用 Canvas 绘制基础能量球
<template>
<canvas ref="energyBallCanvas" width="200" height="200"></canvas>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const energyBallCanvas = ref(null)
onMounted(() => {
const ctx = energyBallCanvas.value.getContext('2d')
function drawEnergyBall(energyLevel) {
ctx.clearRect(0, 0, 200, 200)
// 绘制渐变球体
const gradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 80)
gradient.addColorStop(0, `rgba(0, 255, 255, ${energyLevel})`)
gradient.addColorStop(1, `rgba(0, 100, 255, ${energyLevel * 0.7})`)
ctx.beginPath()
ctx.arc(100, 100, 80, 0, Math.PI * 2)
ctx.fillStyle = gradient
ctx.fill()
// 添加发光效果
ctx.shadowBlur = 20 * energyLevel
ctx.shadowColor = 'cyan'
}
let energy = 0.5
drawEnergyBall(energy)
})
</script>
添加动态能量波动效果
// 在 onMounted 内添加动画循环
function animate() {
energy = 0.5 + Math.sin(Date.now() * 0.005) * 0.2
drawEnergyBall(energy)
requestAnimationFrame(animate)
}
animate()
实现交互控制
<template>
<canvas
ref="energyBallCanvas"
width="200"
height="200"
@mousemove="handleMouseMove"
@click="handleClick"
></canvas>
</template>
<script setup>
// 添加交互方法
function handleMouseMove(e) {
const rect = energyBallCanvas.value.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
// 根据鼠标位置调整能量
const distance = Math.sqrt(Math.pow(x - 100, 2) + Math.pow(y - 100, 2))
energy = Math.max(0, 1 - distance / 100)
}
function handleClick() {
// 点击时爆发能量
energy = 1.0
setTimeout(() => energy = 0.5, 500)
}
</script>
使用 SVG 实现替代方案
<template>
<svg width="200" height="200">
<defs>
<radialGradient id="energyGradient" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="cyan" />
<stop offset="100%" stop-color="blue" />
</radialGradient>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="5" result="blur" />
<feComposite in="SourceGraphic" in2="blur" operator="over" />
</filter>
</defs>
<circle
cx="100"
cy="100"
r="80"
fill="url(#energyGradient)"
:filter="energy > 0.7 ? 'url(#glow)' : ''"
:opacity="energy"
/>
</svg>
</template>
能量数据绑定
// 添加响应式能量数据
const energy = ref(0.5)
// 模拟能量变化
setInterval(() => {
energy.value = Math.min(1, Math.max(0, energy.value + (Math.random() - 0.45) * 0.1))
}, 500)
性能优化建议
- 对于复杂动画,考虑使用 WebGL 替代 Canvas
- 使用 Vue 的 v-once 指令渲染静态部分
- 通过 requestAnimationFrame 节流更新频率
- 对频繁变化的属性使用 CSS 硬件加速
以上方法可根据具体需求组合使用,创建不同风格的能量球效果。







