116182878958338588
前言
GSAP – A wildly robust JavaScript animation library built for professionals(官网)
引入依赖
1
| <script src="https://unpkg.com/gsap@3/dist/gsap.min.js"></script>
|
获取GSAP对象
通过id选择器获取DOM
1 2 3 4 5 6 7
| <svg> <rect id="rect" x="10" y="10" width="10" height="10"></rect> </svg>
<script> gsap.to("#rect", {}); </script>
|
通过DOM对象获取DOM
1 2 3 4 5 6 7
| <svg> <rect id="rect" x="10" y="10" width="10" height="10"></rect> </svg>
<script> gsap.to(document.querySelectorAll("#rect"), {}); </script>
|
通过数组定义多个选择器
1 2 3 4 5 6 7 8
| <svg> <rect id="react1" x="10" y="10" width="10" height="10"></rect> <rect id="react2" x="10" y="10" width="10" height="10"></rect> </svg>
<script> gsap.to(["#rect1", document.querySelectorAll("#react2")], {}); </script>
|
补间动画(Tween)
GSAP可以为所有CSS属性设置动画
以下是部分CSS属性在GSAP中的简写
| CSS属性 |
GSAP属性 |
transform: translateX(10px) |
x: 10 |
transform: translateY(10px) |
y: 10 |
transform: translateX(10%) |
xPercent: 10 |
transform: translateY(10%) |
yPercent: 10 |
transform: rotate(360deg) |
rotation: 360 |
transform: scale(10, 10) |
scale: 10 |
transformOrigin: 0% 0% |
transformOrigin: "0% 0%" |
定义动画结束状态
x:修改后的属性名
20:修改后的属性值
duration:动画持续时间,单位秒,缺省值为0.5
repeat:额外的重复执行次数,缺省值为0,
transformOrigin:定义动画原点
center:缺省值,居中
top:顶部
bottom:底部
left:居左
right:居右
ease:速度曲线
power1.out:缺省值
1 2 3
| gsap.to("#rect", { x: 20 });
|
定义动画开始状态
x:修改后的属性名
20:修改后的属性值
1 2 3
| gsap.from("#rect", { x: 20 });
|
定义动画开始和结束状态
- 必须在最后一个对象中定义
duration
- 后面对象中的
duration会覆盖前面对象的duration,所以无论前面对象是否设置duration都没有意义
- 如果后面对象没有设置
duration,则duration的值为缺省值
1 2 3 4 5 6 7 8 9
| gsap.fromTo( "#rect", { x: 20, }, "#rect", { x: 20, duration: 1 } );
|
动画时间线
1 2 3 4 5
| const timeline = gsap.timeline();
timeline.from("#rect", {}); timeline.to("#rect", {}); timeline.fromTo("#rect", {}, {});
|
1 2 3 4
| const timeline = gsap.timeline() .from("#rect", {}) .to("#rect", {}) .fromTo("#rect", {}, {});
|
完成