网站首页 > 基础教程 正文
搭建 Vue 3 脚手架:
pnpm create vue@latest
安装 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() 三个动画方法,它们各自作用如下:
- .to() 从当前位置移动到目标位置
- .from() 从源位置移动到当前位置
- .fromTo() 从源位置移动到目标位置
- .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
- 上一篇: 520最强PHP表白代码来了
- 下一篇: dom 操作总出错?1 个模板引用技巧
猜你喜欢
- 2025-05-27 是时候使用iframe延迟加载来提升LCP!
- 2025-05-27 页面卡顿到崩溃?5 个实战技巧让前端性能飙升 80%!
- 2025-05-27 前端人必看!10 个实战优化技巧,让项目性能直接起飞!
- 2025-05-27 快速了解JavaScript的表单操作
- 2025-05-27 来了!JavaScript 最强大的 8 个 DOM API
- 2025-05-27 如何使用 ChatGPT 进行抓取
- 2025-05-27 Pyppeteer爬虫神器详解
- 2025-05-27 《高性能JavaScript》学习笔记——日更中
- 2025-05-27 性能狂飙!5 各前端优化奇招,让页面加载速度提升 300%?
- 2025-05-27 前端页面中,如何让用户回到上次阅读的位置?
- 最近发表
-
- 在使用Bootstrap吗?快来看看如何使用 Bootswatch 主题吧
- 50个HTML5免费的Bootstrap模板 :下
- 定制你的bootstrap之--修改less文件1
- BootstrapBlazor :使用 .NET 生成交互式客户端 Web UI 的框架
- React与使用Bootstrap5模态框的注意事项
- 如何引用bootstrap没有的字体图标
- 10个超酷炫Bootstrap HTML & CSS UI工具包
- Bootstrap自举电路工作原理讲解(自举电路的原理)
- 为何 BootstrapVue 能成为 Vue 前端框架顶流?
- 新增 创意布局企业网络服务CSS模板 bootstrap 模板
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)