vue实现点亮灯光
vue实现点亮灯光效果
使用CSS动画和v-bind
通过v-bind动态绑定class实现灯光开关效果。定义一个lightOn的data属性控制灯光状态,点击事件切换该属性值。

<template>
<div>
<div
class="light"
:class="{ 'on': lightOn }"
@click="toggleLight"
></div>
</div>
</template>
<script>
export default {
data() {
return {
lightOn: false
}
},
methods: {
toggleLight() {
this.lightOn = !this.lightOn
}
}
}
</script>
<style>
.light {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #ccc;
transition: all 0.3s ease;
}
.light.on {
background-color: yellow;
box-shadow: 0 0 20px yellow;
}
</style>
结合Canvas绘制发光效果
对于更复杂的发光效果,可以使用Canvas绘制。通过requestAnimationFrame实现流畅的动画。

<template>
<canvas ref="lightCanvas" width="200" height="200"></canvas>
</template>
<script>
export default {
mounted() {
this.drawLight()
},
methods: {
drawLight() {
const canvas = this.$refs.lightCanvas
const ctx = canvas.getContext('2d')
let radius = 0
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 绘制发光效果
const gradient = ctx.createRadialGradient(
100, 100, 0,
100, 100, radius
)
gradient.addColorStop(0, 'rgba(255, 255, 0, 1)')
gradient.addColorStop(1, 'rgba(255, 255, 0, 0)')
ctx.fillStyle = gradient
ctx.beginPath()
ctx.arc(100, 100, radius, 0, Math.PI * 2)
ctx.fill()
radius = (radius + 1) % 100
requestAnimationFrame(animate)
}
animate()
}
}
}
</script>
使用第三方动画库
安装GSAP等动画库可以实现更专业的灯光效果。通过npm安装后,在组件中使用。
npm install gsap
<template>
<div ref="lightElement" class="light"></div>
</template>
<script>
import { gsap } from 'gsap'
export default {
mounted() {
this.animateLight()
},
methods: {
animateLight() {
gsap.to(this.$refs.lightElement, {
duration: 1,
boxShadow: '0 0 30px yellow',
backgroundColor: 'yellow',
repeat: -1,
yoyo: true
})
}
}
}
</script>
<style>
.light {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #ccc;
}
</style>
SVG实现动态灯光
使用SVG结合Vue的动态绑定,创建可交互的灯光效果。
<template>
<svg width="200" height="200">
<circle
cx="100"
cy="100"
:r="radius"
:fill="lightColor"
@click="toggleLight"
/>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="5" result="blur"/>
<feComposite in="SourceGraphic" in2="blur" operator="over"/>
</filter>
</svg>
</template>
<script>
export default {
data() {
return {
radius: 50,
lightColor: '#ccc'
}
},
methods: {
toggleLight() {
this.lightColor = this.lightColor === '#ccc' ? 'yellow' : '#ccc'
this.radius = this.radius === 50 ? 60 : 50
}
}
}
</script>






