专业编程基础技术教程

网站首页 > 基础教程 正文

在 Vue 3 中使用 GSAP 动画库

ccvgpt 2025-05-27 12:57:27 基础教程 4 ℃

搭建 Vue 3 脚手架:

pnpm create vue@latest

安装 GSAP 库:

在 Vue 3 中使用 GSAP 动画库

pnpm add gsap

清空 src/App.vue 原有代码,编写一个蓝色方块,点击该蓝色方块,让它在 1 秒内向右移动 200px。

<template>
    <div class="rect" @click="handleClick"></div>
</template>

<script setup>
  import gsap from 'gsap';

  function handleClick() {
    gsap.to('.rect', { x: 200, duration: 1 })
  }
</script>

<style>
  .rect {
    width: 100px;
    height: 100px;
    background: skyblue;
  }
</style>

点击后,位置会发生位移。

在上面的代码中,gsap.to() 表示从当前位置向目标位置移动。除此之外,还有 .from(), .fromTo() 和 .set() 三个动画方法,它们各自作用如下:

  1. .to() 从当前位置移动到目标位置
  2. .from() 从源位置移动到当前位置
  3. .fromTo() 从源位置移动到目标位置
  4. .set() “瞬移”到目标位置,没有缓动时间

如果想设定旋转角度,使用 rotation 属性。比如,以下代码让方块向右移动的过程中,顺时针旋转 360 度:

gsap.to('.rect', { x: 200, rotation: 360, duration: 1 })

设定缩放大小,使用 scale 属性。比如,以下代码让方块变为原来一半大小:

gsap.to('.rect', { scale: 0.5, duration: 1 })

你可能已经注意到了,我们使用 '.rect' 选择方块。因为 gsap 内部其实会调用 document.querySelectorAll() 方法,因此你可以使用任意合法的选择符。

如果在页面中有多个类名为 "rect" 的方块,它们会同时出现动画效果。

当然,在 Vue 3 中,你也可以使用模板引用(ref)指定动画元素。

<template>
  <div class="rect" ref="myRect" @click="handleClick"></div>
</template>

<script setup>
  import { ref } from 'vue';
  import gsap from 'gsap';

  const myRect = ref(null);
  function handleClick() {
    gsap.to(myRect.value, { x: 200, duration: 1 })
  }
</script>

如果要设定重复次数,使用 repeat 属性。这个属性经常和 yoyo 属性搭配使用,实现往复动画效果。

gsap.to('.rect', { x: 200, repeat: 3, duration: 1, yoyo: true })

设定动画缓动效果,使用 ease 属性。不同的缓动效果,会赋予动画不同的性格,有的沉稳,有的顽皮。

gsap.to('.rect', { x: 200, duration: 1, ease: 'bounce.out' })

GSAP 内置许多缓动函数,使用官方的 Ease Visualizer 可视化工具,可以直观感受每个缓动的实际效果。

参考资料

  • GSAP 快速入门 https://gsap.com/resources/get-started
  • 缓动效果可视化工具 https://gsap.com/resources/getting-started/Easing

最近发表
标签列表