vue实现跑车
Vue 实现跑车动画效果
在 Vue 中实现跑车动画效果可以通过 CSS 动画、JavaScript 动画库或结合 Canvas/SVG 来实现。以下是几种常见的方法:
使用 CSS 动画和过渡
通过 Vue 的 v-bind:style 或 v-bind:class 动态控制跑车的移动和样式变化。

<template>
<div class="road">
<div
class="car"
:style="{ left: carPosition + 'px' }"
></div>
<button @click="moveCar">加速</button>
</div>
</template>
<script>
export default {
data() {
return {
carPosition: 0,
speed: 5
};
},
methods: {
moveCar() {
this.carPosition += this.speed;
}
}
};
</script>
<style>
.road {
width: 100%;
height: 100px;
background: #333;
position: relative;
overflow: hidden;
}
.car {
width: 100px;
height: 50px;
background: red;
position: absolute;
bottom: 0;
transition: left 0.1s linear;
}
</style>
使用 GSAP 动画库
GSAP 是一个强大的 JavaScript 动画库,可以轻松实现复杂的跑车动画效果。

<template>
<div class="road">
<div ref="car" class="car"></div>
<button @click="animateCar">启动</button>
</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
methods: {
animateCar() {
gsap.to(this.$refs.car, {
x: 500,
duration: 2,
ease: "power1.out"
});
}
}
};
</script>
<style>
.road {
width: 100%;
height: 100px;
background: #333;
position: relative;
overflow: hidden;
}
.car {
width: 100px;
height: 50px;
background: blue;
position: absolute;
bottom: 0;
left: 0;
}
</style>
使用 Canvas 绘制跑车
Canvas 提供了更灵活的绘图能力,适合实现更复杂的跑车动画。
<template>
<canvas ref="canvas" width="800" height="200"></canvas>
<button @click="startAnimation">开始</button>
</template>
<script>
export default {
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.carX = 0;
},
methods: {
drawCar(x) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = 'green';
this.ctx.fillRect(x, 100, 100, 50);
},
startAnimation() {
const animate = () => {
this.carX += 5;
this.drawCar(this.carX);
if (this.carX < this.canvas.width) {
requestAnimationFrame(animate);
}
};
animate();
}
}
};
</script>
使用 SVG 实现跑车
SVG 是矢量图形,适合实现可缩放的跑车动画。
<template>
<svg width="800" height="200">
<rect
ref="car"
x="0"
y="100"
width="100"
height="50"
fill="orange"
/>
<button @click="animateCar">移动</button>
</svg>
</template>
<script>
export default {
methods: {
animateCar() {
const car = this.$refs.car;
let pos = 0;
const id = setInterval(() => {
if (pos >= 700) {
clearInterval(id);
} else {
pos += 5;
car.setAttribute('x', pos);
}
}, 20);
}
}
};
</script>
关键点总结
- CSS 动画适合简单的跑车移动效果,通过 Vue 的数据绑定控制样式变化。
- GSAP 提供了更丰富的动画功能,如缓动效果和复杂的时间线控制。
- Canvas 适合需要自定义绘制和更复杂动画的场景。
- SVG 适合需要矢量图形和缩放效果的跑车动画。
根据项目需求选择合适的技术方案,结合 Vue 的响应式特性可以实现动态控制的跑车动画效果。






