vue实现跑车
Vue 实现跑车动画
使用 Vue 结合 CSS 动画可以实现一个简单的跑车动画效果。以下是一个完整的实现示例:
创建 Vue 组件
<template>
<div class="road">
<div class="car" :style="{ left: carPosition + 'px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
carPosition: 0,
animationId: null
}
},
mounted() {
this.animateCar()
},
beforeUnmount() {
cancelAnimationFrame(this.animationId)
},
methods: {
animateCar() {
const speed = 3
this.carPosition += speed
if (this.carPosition > window.innerWidth) {
this.carPosition = -100
}
this.animationId = requestAnimationFrame(this.animateCar)
}
}
}
</script>
添加 CSS 样式
.road {
position: relative;
width: 100%;
height: 100px;
background-color: #555;
overflow: hidden;
}
.car {
position: absolute;
width: 100px;
height: 50px;
background-color: red;
bottom: 0;
border-radius: 10px 10px 0 0;
}
.car::before,
.car::after {
content: '';
position: absolute;
width: 30px;
height: 30px;
background-color: #333;
border-radius: 50%;
bottom: -15px;
}
.car::before {
left: 10px;
}
.car::after {
right: 10px;
}
更高级的实现
如果需要更真实的跑车效果,可以使用 SVG 或图片:
<template>
<div class="road">
<img
class="car"
src="https://example.com/car.png"
:style="{
left: carPosition + 'px',
transform: `scaleX(${direction})`
}"
>
</div>
</template>
<script>
export default {
data() {
return {
carPosition: 0,
direction: 1,
animationId: null
}
},
methods: {
animateCar() {
this.carPosition += 3 * this.direction
if (this.carPosition > window.innerWidth) {
this.direction = -1
} else if (this.carPosition < 0) {
this.direction = 1
}
this.animationId = requestAnimationFrame(this.animateCar)
}
}
}
</script>
使用第三方动画库
对于更复杂的动画效果,可以考虑使用 GSAP 或 Anime.js:
import gsap from 'gsap'
methods: {
animateWithGSAP() {
gsap.to(this.$refs.car, {
x: window.innerWidth,
duration: 5,
ease: "power1.inOut",
onComplete: () => {
gsap.to(this.$refs.car, {
x: 0,
duration: 5,
ease: "power1.inOut"
})
}
})
}
}
注意事项
- 使用
requestAnimationFrame可以获得更流畅的动画效果 - 在组件销毁时记得取消动画帧请求
- 对于移动端需要考虑性能优化
- 可以使用 CSS transform 代替直接修改位置属性以获得更好的性能







