Detailed tween.js Chinese User guide

Source: Internet
Author: User

A tween (animation) is a concept that allows you to change the properties of an object in a smooth manner. You just need to tell it which properties to change, what final values they should have at the end of the tween run, and how long it will take for the tween engine to calculate the value from the start point to the end point.

For example, a position object has x and y two coordinates:

var position = {x:100, y:0}

If you want to change the value of the X coordinate from 100 to 200, you should do this:

First create a tween (tween) var tween = new Tween for the location. Tween (position);//Then tell Tween we want to animate the position of x within 1000 milliseconds tween.to ({x:200}, 1000);

Generally this is not enough, tween has been created, but it has not been activated (use), you need to start this way:

Start Tween.start ();

Finally, to successfully complete this effect, you need to call tween.update in the main function, using the following:

Animate (); function animate () {requestanimationframe (animate);//[...] Tween.update (); // [...]}

This will run the motion tween when each frame is updated, and after 1 seconds (1000 milliseconds) the position.x will become 200.

Unless you print out the value of x in the console, you won't see it change. You may want to use the OnUpdate callback:

Tween.onupdate (function (object) {Console.log (object.x);});

Tips: You may not get object.x here, specifically see my mention of this issue

This function will be called every time the animation is updated, depending on a number of factors-for example, how fast the computer or device is (and how busy) it is.

So far, we've only used tweened animations to output values to the console, but you can combine it with the Three.js object:

var tween = new Tween. Tween (Cube.position). to ({x:100, y:100, z:100}, 10000). Start (); animate (); function animate () {Requestanimationframe ( Animate); Tween.update (); Threerenderer.render (scene, camera);}

In this case, because the three.js renderer will see the object's position before rendering, there is no need to use an explicit OnUpdate callback.

You may also notice a number of different places: Tween.js can be chained to call! Each tween function returns a tween instance, so you can rewrite the following code:

var tween = new Tween. Tween (position); Tween.to ({x:200}, +); Tween.start ();

Change to this:

var tween = new Tween. Tween (position). to ({x:200}, +). Start ();

There will be a lot of examples, so it's good to be familiar with it! such as the 04-simplest example.

Tween.js's Animation

Tween.js does not run on its own. You need to explicitly call the Update method to tell it when to run. The recommended approach is to perform this operation in the active draw loop. Use Requestanimationframe to call this loop for optimal graphics performance.

As in the previous example:

Animate (); function animate () {requestanimationframe (animate);//[...] Tween.update (); // [...]}

If you do not pass in a parameter when calling, update will determine the current point in time to determine how long it has been since it was last run.

Of course you can also pass a definite time parameter to the update

Tween.update (100);

This means "update time = 100 milliseconds". You can use it to ensure that all time-related functions in your code use the same time values. For example, suppose you have a player and want to run the tween synchronously. Your animate function might look like this:

var currenttime = Player.currenttime; Tween.update (currenttime);

We use explicit time values for unit testing. You can look at the example of tests.js and see how we call Tween.update () with different values to simulate time passing.

Control a Tween

Start and stop

So far, we've learned about the Tween.start method, but there are more ways to control a single tween. Perhaps the most important one is the method that star corresponds to: Stop. If you want to cancel a tween, just call this method through a separate tween:

Tween.stop ();

Stopping a tween that has never started or stopped has no effect. No errors were thrown.

The Start method takes a parameter time. If you use it, the tween will not start immediately until a specific moment, otherwise it will start as soon as possible (i.e is the next call to Tween.update).

Update

The tween also has an updated method---this is actually called by Tween.update. You don't usually need to call it directly unless you're a crazy hacker.

Chain

When you arrange different tweens in order, things become interesting, such as starting another tween immediately at the end of the last tween. We call this a chained tween, which is done using the chain method. Therefore, in order for the Tweenb to start in Tewwna:

Tweena.chain (TWEENB);

Or, for an infinite chain, set Tweena to start once the Tweenb is complete:

Tweena.chain (TWEENB); Tweenb.chain (Tweena);

See Hello World for an infinite chain.

In other cases, you may want to link multiple tweens to another tween so that they (linked tweens) Start the animation at the same time:

Tweena.chain (TWEENB,TWEENC);

Warning: Calling Tweena.chain (TWEENB) actually modifies Tweena, so Tweena is always started when Tweena is complete. The return value of chain is only Tweena, not a new tween.

Repeat

If you want a tween to repeat forever, you can link to yourself, but the better way is to use the Repeat method. It takes a parameter that describes how many repetitions are required after the first tween completes

Tween.repeat (10); Circulation 10 times tween.repeat (Infinity); Infinite loops

The total number of tweens will be a repeating parameter plus an initial tween. View Repeat.

Yoyo

This function is only effective when using repeat alone. When active, the tween behaves like Yoyo, i.e it jumps from the start and end values rather than repeating the same order from the beginning.

Delay

More complex arrangements may require that the tween be deferred before the actual start of the operation. You can use the delay method to do this

Tween.delay (+); Tween.start ();

Execution starts 1 seconds after the start method is called.

Control all Tweens

The following methods can be found in the TWEEN global object, and most of these objects are not normally needed in addition to update.

Tween.update (Time)

We have discussed this approach. It is used to update all active tweens.

If time is not specified, it will use the current times.

Tween.getall and Tween.removeall

Used to get a reference to an active tweens array and remove all of them from the array, respectively, from only one invocation

Tween.add (TWEEN) and Tween.remove (TWEEN)

Used to add a tween to the list of active tweens, or to remove a specific tween from the list, respectively.

These methods are usually used only internally, but are exposed if you want to do something interesting.

Control tween Groups

Using the TWEEN Singleton to manage tweens can cause problems for large applications that contain many components. In these cases, you may want to create your own smaller tween group.

Example: Cross component conflict

If you use TWEEN with multiple components, and each component wants to manage its own set of tweens, a conflict can occur. If a component calls Tween.update () or Tween.removeall (), the tween of the other component will also be updated or deleted.

Create your own tween group

To solve this problem, each component can create its own TWEEN. The Group instance (which is used internally by the global TWEEN object). When you instantiate a new tween, you can pass these groups as the second optional parameter:

var groupa = new TWEEN. Group (); var GroupB = new TWEEN. Group (); var Tweena = new TWEEN. Tween ({x:1}, Groupa). to ({x:10}, +). Start (); var tweenb = new Tween. Tween ({x:1}, GroupB). to ({x:10}, +). Start (); var tweenc = new Tween. Tween ({x:1}). to ({x:10}, +). Start (); Groupa.update (); Update only tweenagroupb.update (); Update only tweenbtween.update (); Update only Tweencgroupa.removeall (); Only remove Tweenagroupb.removeall (); Only remove Tweenbtween.removeall (); Only remove Tweenc

In this way, each component can handle creating, updating, and destroying its own set of tweens.

Change Ease function

Tween.js will perform the interpolation (i.e. easing) between values in a linear manner, so the change will be proportional to the elapsed time. This is predictable, but visually rather uninteresting. Don't worry-you can easily change this behavior by using the easing method. For example:

Tween.easing (Tween. EASING.QUADRATIC.IN);

This will result in a slow start to the final value change, accelerating to the middle, and then quickly reaching its final value, instead, TWEEN. Easing.Quadratic.Out accelerates at first, but slows down as the value approaches.

Available easing functions: tween.easing

Tween.js provides some of the existing easing functions. They are grouped according to the equations they represent: linear, two, three, four, five, sinusoidal, exponential, rounded, elastic, back and bouncing, then slow: In,out and inout.

Unless you're already familiar with these concepts, these names might not say anything to you, so you might want to look at the Graphs example, which graphically graphs all the curves in a page to compare how they look at a glimpse.

These features were generously derived from Robert Penner's original equations, which were provided a few years ago as free software, but have been optimized to work well with JavaScript.

Using the custom easing feature

Not only can you use any of the existing features, you can also provide your own functionality, as long as you follow some conventions:

It must accept a parameter:

K: How long is the easing process, or how much time we have in the tween. The allowable values are within the range of [0,1].

It must return a value based on the input parameters.

The easing function is called only once per update, regardless of the number of properties you want to modify. The result is then used in conjunction with the initial value and the difference between the value and the final value (delta), just like this pseudo code:

easedelapsed = easing (k); for each property:newpropertyvalue = initialpropertyvalue + Propertydelta * easedElapsed;

For people who pay more attention to performance, the increment value is calculated only when start () is called on the tween.

So let's assume that you want to use a custom easing function with a mitigation value, but apply Math.floor to the output, so only the integer part is returned, resulting in a cascade output:

function Tenstepeasing (k) {return Math.floor (k * 10)/10;}

You can use it simply by invoking its easing method, as we saw earlier:

Tween.easing (tenstepeasing);

View the graphs for custom easing functions example to see this action (there are also meta-programming for generating stepping functions).

callback function

Another powerful feature is the ability to run its own functionality at a specific time in the life cycle of each tween. This is usually required when changing properties are not sufficient.

For example, suppose you are trying to animate an object that does not have direct access to the property, but you need to call the setter. You can use the update callback to read the new update value and then call setters manually. All of the callback functions use the Tweened object as a unique parameter.

var trickyobjtween = new TWEEN. Tween ({PropertyA:trickyObj.getPropertyA (), PropertyB:trickyObj.getPropertyB ()}). to ({propertya:100, propertyb:200 }). onUpdate (Function (object) {Object.seta (Object.propertya); Object.setb (OBJECT.PROPERTYB);});

Or imagine that when a tween starts, you want to play the sound. You can use the start callback:

var tween = new Tween. Tween (obj). to ({x:100}). OnStart (function () {Sound.play ();});

The scope of each callback is the tween object-in this case, obj.

OnStart

Executes the--i.e before the tween begins. Before the calculation. Each tween can only be executed once, i.e. when a tween is repeated through repeat (), it will not run.

It is good to sync to other events or to trigger actions that occur when you start a tween.

A tweened object is passed in as the first parameter.

OnStop

The tween is executed when the tween is explicitly stopped by Stop (), but when it is completed normally and before any possible chain tweens are stopped.

A tweened object is passed in as the first parameter.

OnUpdate

The value that is actually updated each time the tweened update is performed.

A tweened object is passed in as the first parameter.

OnComplete

Executes when the tween is completed normally (that is, does not stop).

A tweened object is passed in as the first parameter.

Superior Tween Room

Relative value

Relative values can also be used when using the To method. When Tween starts, Tween.js reads the current property value and applies a relative value to find the new final value.

But you need to use quotation marks, otherwise these values will be treated as absolute. Let's look at an example:

The ' X ' property is Alwaysvar absolutetween = new TWEEN. Tween (Absoluteobj) to ({x:100});//Suppose absoluteobj.x is 0 nowabsolutetween.start (); Makes x go to 100//suppose absoluteobj.x is-100 nowabsolutetween.start (); Makes x go to 100//in contrast...//this would make the ' X ' property is units more,//relative to the actual value When it startsvar Relativetween = new TWEEN. Tween (Relativeobj) to ({x: "+100"});//Suppose relativeobj.x is 0 nowrelativetween.start (); Makes x go to 0 +100 = 100//Suppose relativeobj.x is-100 nowrelativetween.start (); Makes x go to-100 +100 = 0

View the 09_relative_values sample.

Array of tween values

In addition to a tween as an absolute or relative value, you can let tween.js change properties across a range of values. To do this, you only need to specify the value of an array, not a single value of an attribute. For example:

var tween = new Tween. Tween (Relativeobj) to ({x: [0,-100, 100]});

Causes X to change from the initial value to 0,-100 and 100.

These values are calculated as follows:

    1. First, the tween progress is calculated as usual
    2. Progress (from 0 to 1) as input to the interpolation function
    3. An array based on progress and values that generates interpolated values

For example, when a tween has just started (with a progress of 0), the interpolation function returns the first value in the array. When the tween is halfway, the interpolation function returns a value about the middle of the array, and when the tween ends, the interpolation function returns the last value.

You can use the interpolation method to change the interpolation function. For example:

Tween.interpolation (Tween. Interpolation.bezier);

The following values are available:

    1. TWEEN. Interpolation.linear
    2. TWEEN. Interpolation.bezier
    3. TWEEN. Interpolation.catmullrom

The default is Linear.

Note that the interpolation function is global for all properties that tween an array in the same tween.
You cannot use array and linear functions to make property a changes, and you cannot use the same tween to change the property B and Bezier functions of array B; You should use two Tweened objects running on the same object, but modify different properties and use different interpolation functions.

View the 06_array_interpolation sample.

Get the best performance

While Tween.js is trying to execute on its own, nothing can stop you from using it in a counterproductive way. Here are some ways to avoid slowing down your project when using Tween.js (or when animating in a Web page).

Using high-performance CSS

When you try to set the position of an element in a page, the simplest solution is to animate the top and left properties as follows:

var element = document.getElementById (' myelement '); var tween = new Tween. Tween ({top:0, left:0}). To ({top:100, left:100}, +). OnUpdate (Function (object) {element.style.top = Object.top + ' px '; Element.style.left = object.left + ' px '; });

This is actually inefficient, because changing these attributes will force the browser to recalculate the layout each time it is updated, which is a very expensive operation. Instead, you should use transform, which does not invalidate the layout and, if possible, hardware acceleration, such as:

var element = document.getElementById (' myelement '); var tween = new Tween. Tween ({top:0, left:0}). To ({top:100, left:100}, +). OnUpdate (Function (object) {Element.style.transform = ' tran Slate (' + object.left + ' px, ' + object.top + ' px); });

However, if your animation needs are very simple, it might be better to use CSS animations or transformations where applicable, so that the browser can optimize as much as possible.
Tween.js is useful when your animation needs to involve complex layouts, that is, you need to synchronize multiple tweens together, after completing some actions, looping multiple times, and so on.

To the garbage collector (alias GC)

If you use the OnUpdate callback function, you need to use it very carefully. Because this function is called many times per second, you can block the main thread and cause dire results if each update takes a lot of cost, or if your operation involves memory allocations, the garbage collector runs too often and results. So just don't do one of those things. Keep your onupdate callbacks very lightweight and make sure that you also use memory analyzers at development time.

Crazy tweens.

This is something you may not use very often, but you can use a tween formula outside of Tween.js. After all, they are just functions. So you can use them to calculate smoothing curves as input data.

Detailed tween.js Chinese User guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.