vue 实现抛物线
Vue 实现抛物线动画
在 Vue 中实现抛物线动画,可以通过 CSS 动画或 JavaScript 动态计算位置来实现。以下是两种常见方法:
方法一:使用 CSS animation 和 @keyframes
通过 CSS 定义抛物线关键帧动画,适用于简单的抛物线效果。
<template>
<div class="ball" :style="{ left: x + 'px', top: y + 'px' }"></div>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0
};
},
mounted() {
this.startAnimation();
},
methods: {
startAnimation() {
const duration = 2000; // 动画时长(毫秒)
const startTime = Date.now();
const animate = () => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
// 抛物线公式:y = a * x^2 + b * x + c
this.x = progress * 300; // 水平位移
this.y = 200 * Math.pow(progress, 2) - 100 * progress; // 垂直位移
if (progress < 1) {
requestAnimationFrame(animate);
}
};
animate();
}
}
};
</script>
<style>
.ball {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
transition: all 0.1s linear;
}
</style>
方法二:使用 GSAP 动画库
GSAP 提供了更强大的动画控制能力,适合复杂的抛物线效果。
<template>
<div ref="ball" class="ball"></div>
</template>
<script>
import { gsap } from 'gsap';
export default {
mounted() {
this.startGSAPAnimation();
},
methods: {
startGSAPAnimation() {
gsap.to(this.$refs.ball, {
duration: 2,
x: 300,
y: 200,
ease: "power1.inOut"
});
}
}
};
</script>
<style>
.ball {
position: absolute;
width: 20px;
height: 20px;
background-color: blue;
border-radius: 50%;
}
</style>
方法三:自定义抛物线函数
通过数学公式动态计算位置,实现更灵活的抛物线效果。
methods: {
parabolicMotion(startX, startY, endX, endY, duration) {
const startTime = Date.now();
const animate = () => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
// 计算当前 x 和 y 坐标
this.x = startX + (endX - startX) * progress;
this.y = startY + (endY - startY) * progress - 200 * Math.pow(progress, 2);
if (progress < 1) {
requestAnimationFrame(animate);
}
};
animate();
}
}
注意事项
- 抛物线公式一般形式为 $y = ax^2 + bx + c$,通过调整系数可以改变抛物线形状。
- 使用
requestAnimationFrame实现平滑动画,避免直接修改 DOM。 - 对于复杂动画,推荐使用 GSAP 或 Anime.js 等专业动画库。







