vue实现点亮灯光
Vue 实现点亮灯光效果
在 Vue 中实现点亮灯光效果可以通过多种方式完成,以下是几种常见的方法:
使用 CSS 动画和 Vue 数据绑定
通过 Vue 的数据绑定控制 CSS 类名,实现灯光的点亮和熄灭效果。
<template>
<div>
<div
class="light"
:class="{ 'light-on': isLightOn }"
@click="toggleLight"
></div>
</div>
</template>
<script>
export default {
data() {
return {
isLightOn: false
}
},
methods: {
toggleLight() {
this.isLightOn = !this.isLightOn
}
}
}
</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>
使用 SVG 和动态样式
通过 SVG 实现更复杂的灯光效果,利用 Vue 控制 SVG 元素的属性。
<template>
<div>
<svg width="200" height="200">
<circle
cx="100"
cy="100"
r="50"
:fill="isLightOn ? 'yellow' : 'gray'"
:filter="isLightOn ? 'url(#glow)' : 'none'"
@click="toggleLight"
/>
<defs>
<filter id="glow" x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation="5" result="blur" />
<feComposite in="SourceGraphic" in2="blur" operator="over" />
</filter>
</defs>
</svg>
</div>
</template>
<script>
export default {
data() {
return {
isLightOn: false
}
},
methods: {
toggleLight() {
this.isLightOn = !this.isLightOn
}
}
}
</script>
使用第三方动画库
结合动画库如 GSAP 或 Anime.js 实现更丰富的灯光动画效果。
<template>
<div>
<div ref="lightBulb" class="light-bulb" @click="toggleLight"></div>
</div>
</template>
<script>
import { gsap } from 'gsap'
export default {
data() {
return {
isLightOn: false
}
},
methods: {
toggleLight() {
this.isLightOn = !this.isLightOn
if (this.isLightOn) {
gsap.to(this.$refs.lightBulb, {
backgroundColor: 'yellow',
boxShadow: '0 0 20px yellow',
duration: 0.5
})
} else {
gsap.to(this.$refs.lightBulb, {
backgroundColor: '#ccc',
boxShadow: 'none',
duration: 0.5
})
}
}
}
}
</script>
<style>
.light-bulb {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #ccc;
cursor: pointer;
}
</style>
结合 Canvas 实现动态灯光
使用 Canvas 绘制更复杂的灯光效果,通过 Vue 控制绘制逻辑。

<template>
<div>
<canvas ref="lightCanvas" width="200" height="200" @click="toggleLight"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
isLightOn: false,
ctx: null
}
},
mounted() {
this.ctx = this.$refs.lightCanvas.getContext('2d')
this.drawLight()
},
methods: {
toggleLight() {
this.isLightOn = !this.isLightOn
this.drawLight()
},
drawLight() {
this.ctx.clearRect(0, 0, 200, 200)
if (this.isLightOn) {
// 绘制发光效果
const gradient = this.ctx.createRadialGradient(100, 100, 0, 100, 100, 50)
gradient.addColorStop(0, 'yellow')
gradient.addColorStop(1, 'transparent')
this.ctx.beginPath()
this.ctx.arc(100, 100, 50, 0, Math.PI * 2)
this.ctx.fillStyle = gradient
this.ctx.fill()
this.ctx.beginPath()
this.ctx.arc(100, 100, 30, 0, Math.PI * 2)
this.ctx.fillStyle = 'yellow'
this.ctx.fill()
} else {
// 绘制关闭状态
this.ctx.beginPath()
this.ctx.arc(100, 100, 30, 0, Math.PI * 2)
this.ctx.fillStyle = '#ccc'
this.ctx.fill()
}
}
}
}
</script>
以上方法可以根据项目需求选择适合的实现方式,从简单的 CSS 动画到复杂的 Canvas 绘制都能实现点亮灯光的效果。






