当前位置:网站首页>Simple usage of GSAP
Simple usage of GSAP
2022-06-28 05:01:00 【Durian is not delicious】
gsap Simple usage
gsap
gsap.from()
Imagine gsap.from() A back room , You define where values should start , Then it animates to the current state , This is ideal for animating objects onto the screen , Because you can set them up the way you want them to see at the end and then animate them from elsewhere . for example :
let tween = gsap.from(".box", {
opacity: 0,
y: 100, // from y=100 Move to current position (y=0)
duration: 1,
yoyo: true,
repeat: -1,
ease: "power2", // Set motion curve , From fast to slow
// event
onRepeat: () => {
console.log('onRepeat'); // The animation repeats (repeat) This event will be triggered when ,
},
});
// We can control him
tween.seek(2); // seek
tween.progress(0.5); // speed of progress
tween.play(); // Start
tween.pause(); // Pause
tween.resume(); // Cancel the suspension
tween.reverse(); // Reverse motion
tween.restart(); // Start over
Items that can be controlled can be viewed file
ease: Adjustable curve , View the motion track
gsap.to()
Same as gsap.from() The animation is the opposite
let tween = gsap.to(".box", {
opacity: 0,
y: 100, // From the current position (y=0) Moving to y=100
duration: 1,
yoyo: true,
repeat: -1,
});
fromTo()
gsap.fromTo() The gap allows you to define the start and end values of the animation ( And using the current state as the start or end from() and to() Make up the opposite ). This is useful for fully controlling animation , Especially when it is linked to other animations
// take “.box” Opacity 0 Set to opacity 0.5
gsap.fromTo(".box", {
opacity: 0}, {
opacity: 0.5, duration: 1});
// example
<h2> Welcome to my world </h2>
<button onclick="pause()">pause</button>
<button onclick="seek()">seek</button>
<button onclick="progress()">progress</button>
<button onclick="play()">play</button>
// Transparency comes from 0 To 0.9
let tween1 = gsap.fromTo("h2", {
opacity: 0 }, {
opacity: 0.9, duration: 4 });
const pause = () => {
tween1.pause();}
const seek = () => {
tween1.seek(2);}
const progress = () => {
tween1.progress(0.5);}
const play = () => {
tween1.play();}
effects: Sign up for animation
// The following is a custom animation . call myfade that will do
gsap.registerEffect({
name: "myfade", // Custom naming
effect: (targets, config) => {
return gsap.to(targets, {
duration: config.duration, opacity: 0 });
},
defaults: {
duration: 2 }, // The default value applies to any... Passed to the effect “config” object
extendTimeline: true, // extendTimeline Set to true, Can be directly in any GSAP Time line call effect
});
gsap.effects.fade("myfade");
let tl = gsap.timeline(); // Want to call timeline,extendTimeline It has to be for true, Otherwise, the report will be wrong
tl.myfade("h3", {
duration: 3 })
.myfade("h4", {
duration: 1 }, "+=2")
.to("h5", {
x: 100 });
getById()
When creating a gap or timeline , You can assign it a id, So that it can be referenced later . This is using frameworks and building tools ( Such as React) It's very useful , Because they are difficult to track variables .
gsap.to(obj, {
id: "myTween", duration: 1, x: 100});
//later
gsap.getById("myTween"); //returns the tween
globalTimeline: Timeline
gsap.globalTimeline It's driving GSAP The root of everything in Timeline example , Will affect all animations .
A useful way
gsap.globalTimeline.pause() - Pause the global timeline that affects all animations . Return to oneself .
gsap.globalTimeline.play() - Restore the global timeline that affects all animations . Return to oneself .
gsap.globalTimeline.paused() -true Returns... If the global timeline is paused .false If the global timeline is playing , Then return to .
gsap.globalTimeline.timeScale() - Gets or sets the global timescale , It is a multiplier that affects all animation . This is actually
<h1>welecome</h1>
<h2> Welcome to my world </h2>
<h3> Welcome to my world </h3>
<button onclick="pauseAll()"> Pause all animation </button>
gsap.from("h1", {
y: 100, duration: 1,yoyo: true, repeat: -1,})
gsap.from("h2", {
x: 100, duration: 2,yoyo: true, repeat: -1,})
gsap.from("h3", {
rotate: 100, duration: 3,yoyo: true, repeat: -1,})
const pauseAll = () => {
gsap.globalTimeline.pause() }
Be careful :
Because the global timeline is used to run all other gaps and timelines , Therefore, no matter whether there is any gap or timeline currently active ,gsap.globalTimeline.isActive() Will always return .true
ticker
gsap.ticker It's like GSAP The heartbeat of the engine -
It updates on each event globalTimelinerequestAnimationFrame, So it's perfectly synchronized with the browser's rendering cycle . You can add your own listeners to run custom logic after each update ( Very suitable for game developers ). Add as many listeners as you need .
Callback Arguments
time : Number - Total time since the code started ( In seconds ). The start time of the code may be lagSmoothing advance .
deltaTime : Number - The number of milliseconds elapsed since the last tick . Be careful : You can use gsap.ticker.deltaRatio() Based on a certain goal FPS Ratio of .
frame : Number - Frames incremented on each scale ( scale ) Number
add()
You can go to Two optional parameters are used in gsap.ticker.add():
once : Boolean - The callback will be triggered only once and then deleted automatically
priority : Boolean - Callbacks will be added to the top of the queue instead of the bottom , This means that it will trigger before any listeners in the current queue . If you want the callback to be in GSAP Before the global timeline of , It's a great fit .
Hide tab time flow
gsap.ticker.fps()
To limit the code to a specific frame rate , You can use the following fps() Method : gsap.ticker.fps(30);
<button onclick="removeTicker()"> Click button , Remove events </button>
function myFunction(time , deltaTime , frame) {
console.log(time); }
gsap.ticker.add(myFunction);
// Remove the listener
function removeTicker() {
gsap.ticker.remove(myFunction);
}
// gsap.ticker.add(myFunction, true, true);
delayedCall()
Return value : Tween
A simple way to call a function after a set time
// 1 Seconds later myFunction() And transmission 2 Parameters :
gsap.delayedCall(1, myFunction, ["param1", "param2"]);
function myFunction(param1, param2) {
//do stuff
}
// To cancel / Terminate deferred call , Please save the reference to it , Then call it when needed .kill() :
var delayedCall = gsap.delayedCall(1, myFunction);
// A moment later
delayedCall.kill();
// If you don't want to keep a reference to it , You can use gsap.killTweensOf() Method , because delayCall() Just with onComplete Of Tween, And the function itself is Tween Of “ The goal is ”:
gsap.delayedCall(1, myFunction);
// A moment later
gsap.killTweensOf(myFunction);
defaults()
Change the default
// Apply to all animations ease and duration
gsap.defaults({
ease: "power2.in",
duration: 1
});
gsap.from("h1", {
y: 100, yoyo: true, repeat: -1, })
gsap.from("h2", {
x: 100, yoyo: true, repeat: -1, })
gsap.from("h3", {
rotate: 100,yoyo: true, repeat: -1, })
gsap.config()
To configure GSAP Non - Tween Specific settings , for example autoSleep、force3D and units, Details can be found in the documentation
// You just need to define the configuration settings you want to change . Omitted attributes are not affected .
gsap.config({
autoSleep: 60,
force3D: false,
nullTargetWarn: false,
trialWarn: false,
units: {
left: "%", top: "%", rotation: "rad"}
});
utils
checkPrefix() Check prefix
clamp() Limit values to a specific range ( for example :clamp(0, 100, -12) --> 0).
distribute() Or assign a value to an array of objects based on their position in the grid , You can choose to apply the jog
getUnit() Get the unit of the string ( for example :getUnit(“30px”) --> “px”).
interpolate() In almost any two values ( Numbers 、 Color 、 character string 、 Array 、 Complex string , Even objects with multiple properties ) Interpolation between ( for example :interpolate(“red”, “blue”, 0.5) --> “rgba(128,0,128,1)”).
mapRange() Mapping one range to another ( for example :mapRange(-10, 10, 0, 100, 5) --> 75).
normalize() Map numbers in the range to 0 To 1 Progress between ( for example :normalize(100, 200, 150) --> 0.5).
pipe() Sort multiple function calls , Pass the result of each function to the next function ( for example :pipe(clamp(0, 100), snap(5))(8) --> 10).
random() Generate a random number according to the parameters ( for example :random(0, 100, 5) --> 65) Or randomly select an element from the array provided ( for example random([“red”, “green”, “blue”]) --> “red”).
selector() Returns a range for a specific element ( or React ref or Angular ElementRef) Selector function of .( for example selector(myElement):)
shuffle() Disrupt the contents of the array in place .( for example :shuffle([1, 2, 3, 4, 5]) --> [4, 2, 1, 5, 3])
snap() Snap values to increments ( for example :snap(5, 13) --> 15) Or the closest value in the array ( for example :snap([0, 5, 10], 7) --> 5).
splitColor() Split any color into its red 、 green 、 Blue ( And optional alpha) component . Or hue 、 Saturation and brightness .( for example :splitColor(“red”) --> [255, 0, 0]).
toArray() Convert almost all array like objects to arrays , Include selector text !( for example :toArray(“.class”) --> [element1, element2]).
unitize() Wrap another utility function , Allow it to accept with "20px" Or something like that "50%“ The value of the unit of , Split units when entering a utility function for the package , Then add it back to the result ( for example var wrap = gsap.utils.unitize( gsap.utils.wrap(0, 100) ); wrap(“150px”); --> “50px”). Or force the use of specific units ( for example :unitize( gsap.utils.mapRange(-10, 10, 0, 100), “%”); --> Always return ”%").
wrap() Place a number in the specified range , So when it exceeds the maximum , It will go back to the beginning , If it is less than the minimum , It will go back to the end ( for example wrap(5, 10, 12) --> 7). Or loop through an array , So when the supplied index is larger than the length of the array , It will return to the beginning ( for example :wrap([0, 10, 20], 4) --> 10).
wrapYoyo() Place a number in the specified range , So when it exceeds the maximum , It will go back to the beginning , If it is less than the minimum , It will go back to the end ( for example wrap(5, 10, 12) --> 7). Or loop through an array , So when the supplied index is larger than the length of the array , It will return to the beginning ( for example :wrap([0, 10, 20], 4) --> 10).
边栏推荐
猜你喜欢
Redis 的 最新windows 版本 5.0.14
并发之wait/notify说明
Where does the storm go? Whose pot is the weather forecast wrong?
PCR/qPCR研究:Lumiprobe丨dsGreen 用于实时 PCR
[noip2002 popularization group] cross the river pawn
[early knowledge of activities] list of recent activities of livevideostack
2022年全国最新消防设施操作员(初级消防设施操作员)模拟题及答案
控制器的功能和工作原理
On the necessity of building a video surveillance convergence platform and its scenario application
OracleData安装问题
随机推荐
【SkyWalking】一口气学完分布式链路追踪SkyWalking
openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
Distributed transaction - Final consistency scheme based on message compensation (local message table, message queue)
Analysis of distributed transaction solution Seata golang
基于订单流工具,我们能看到什么?
别卷!如何高质量地复现一篇论文?
Operation of simulated examination platform of G3 boiler water treatment recurrent training question bank in 2022
2022年G3锅炉水处理复训题库模拟考试平台操作
控制器的功能和工作原理
Cgo+gsoap+onvif learning summary: 8. Summary of arm platform cross compilation operation and common problems
JS 文本框失去焦点修改全半角文字和符号
cgo+gSoap+onvif学习总结:8、arm平台交叉编译运行及常见问题总结
二级造价工程师证书含金量到底有多高?看这些就知道了
【JVM系列】JVM调优
[csp-j2020] excellent splitting
深度强化学习笔记
2022烟花爆竹经营单位安全管理人员特种作业证考试题库及模拟考试
Notepad++ -- common plug-ins
Meta universe standard forum established
Feign remote call fallback callback failed, no effect