vue实现跑车
Vue 实现跑车动画效果
使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案:
创建 Vue 组件结构
<template>
<div class="road">
<div class="car" :style="carStyle"></div>
</div>
</template>
添加组件样式
<style scoped>
.road {
width: 100%;
height: 200px;
background-color: #333;
position: relative;
overflow: hidden;
}
.car {
width: 100px;
height: 50px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50"><rect x="10" y="15" width="80" height="20" fill="red"/><circle cx="25" cy="45" r="10" fill="black"/><circle cx="75" cy="45" r="10" fill="black"/></svg>');
background-repeat: no-repeat;
position: absolute;
bottom: 20px;
}
</style>
实现动画逻辑
<script>
export default {
data() {
return {
position: 0,
direction: 1,
speed: 2
}
},
computed: {
carStyle() {
return {
left: `${this.position}px`,
transform: `scaleX(${this.direction})`
}
}
},
mounted() {
this.animateCar()
},
methods: {
animateCar() {
const animate = () => {
this.position += this.speed * this.direction
if (this.position > window.innerWidth - 100) {
this.direction = -1
} else if (this.position < 0) {
this.direction = 1
}
requestAnimationFrame(animate)
}
animate()
}
}
}
</script>
进阶优化方案
添加道路标记和更流畅的动画效果:
.road::before {
content: "";
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 10px;
background: repeating-linear-gradient(
to right,
white,
white 20px,
transparent 20px,
transparent 40px
);
}
使用 GSAP 实现更复杂动画
安装 GSAP 库:
npm install gsap
在组件中使用:
import { gsap } from 'gsap'
methods: {
animateWithGSAP() {
gsap.to(this.$data, {
position: window.innerWidth - 100,
duration: 3,
ease: "power1.inOut",
onComplete: () => {
gsap.to(this.$data, {
position: 0,
duration: 3,
ease: "power1.inOut",
onComplete: this.animateWithGSAP
})
}
})
}
}
响应式调整
添加窗口大小变化的监听:
mounted() {
this.animateCar()
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
if (this.position > window.innerWidth - 100) {
this.position = window.innerWidth - 100
}
}
}
以上实现提供了从基础到进阶的跑车动画方案,可根据实际需求调整速度、方向和视觉效果。







