vue实现跑车
Vue 实现跑车动画
在 Vue 中实现跑车动画可以通过 CSS 动画或 JavaScript 动画库(如 GSAP)来实现。以下是一个基于 CSS 动画的跑车动画实现方法:
创建 Vue 组件
创建一个 Vue 单文件组件(SFC),命名为 CarAnimation.vue。组件包含跑车的 HTML 结构和样式。
<template>
<div class="car-container">
<div class="car">
<div class="car-body"></div>
<div class="car-wheel front-wheel"></div>
<div class="car-wheel back-wheel"></div>
</div>
</div>
</template>
<script>
export default {
name: 'CarAnimation'
}
</script>
<style scoped>
.car-container {
width: 100%;
height: 200px;
position: relative;
overflow: hidden;
background-color: #f0f0f0;
}
.car {
position: absolute;
bottom: 20px;
left: -100px;
animation: drive 4s linear infinite;
}
.car-body {
width: 150px;
height: 50px;
background-color: red;
border-radius: 10px;
position: relative;
}
.car-wheel {
width: 30px;
height: 30px;
background-color: black;
border-radius: 50%;
position: absolute;
bottom: -15px;
animation: spin 1s linear infinite;
}
.front-wheel {
right: 10px;
}
.back-wheel {
left: 10px;
}
@keyframes drive {
0% {
transform: translateX(-100px);
}
100% {
transform: translateX(100vw);
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
动画说明
drive动画:控制跑车从左侧移动到右侧,通过transform: translateX实现水平移动。spin动画:控制车轮旋转,通过transform: rotate实现旋转效果。
使用组件
在父组件中引入并使用 CarAnimation 组件:

<template>
<div>
<CarAnimation />
</div>
</template>
<script>
import CarAnimation from './CarAnimation.vue'
export default {
components: {
CarAnimation
}
}
</script>
增强动画效果
如果需要更复杂的跑车动画(如加速、减速或路径变化),可以使用 GSAP 库:
-
安装 GSAP:

npm install gsap -
修改
CarAnimation.vue使用 GSAP:<template> <div ref="carContainer" class="car-container"> <div ref="car" class="car"> <div class="car-body"></div> <div class="car-wheel front-wheel"></div> <div class="car-wheel back-wheel"></div> </div> </div> </template>
export default { name: 'CarAnimation', setup() { const car = ref(null) const carContainer = ref(null)
onMounted(() => {
const containerWidth = carContainer.value.offsetWidth
gsap.to(car.value, {
x: containerWidth + 100,
duration: 4,
ease: "power1.inOut",
repeat: -1
})
})
return { car, carContainer }
} }
```通过 GSAP 可以实现更灵活的动画控制,如缓动效果和循环动画。






