search
HomeWeb Front-endJS TutorialDetailed explanation of usage examples of tween.js

Detailed explanation of usage examples of tween.js

Sep 16, 2017 am 09:36 AM
javascriptDetailed explanation

This article mainly introduces the detailed explanation of how to use tween.js. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Previous words

TweenJS provides a simple but powerful gradient interface. It supports gradient digital object properties & CSS style properties, and allows linked tweened animations and actions to be combined to create complex sequences. This article will introduce the use of tween.js in detail

Overview

tween.js allows to modify the attribute values ​​​​of elements in a smooth way. You only need to tell tween what value you want to modify, what its final value will be when the animation ends, how long the animation takes, and other information. The tween engine can calculate the value from the start animation point to the end animation point to produce a smooth animation effect.

For example, suppose there is an object position whose coordinates are x and y:


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

If you want to change the value of x from 100 to 200, just You need to do this:


// Create a tween for position first
var tween = new TWEEN.Tween(position);
 
// Then tell the tween we want to animate the x property over 1000 milliseconds
tween.to({ x: 200 }, 1000);

Here you just created the tween object, you need to activate it and let it start animation:


// And set it to start
tween.start();

Finally, in order to smooth the animation effect, the TWEEN.update method needs to be called in the same loop animation. The code is as follows:


animate();
 
function animate() {
  requestAnimationFrame(animate);
  // [...]
  TWEEN.update();
  // [...]
}

This action will update all activated tweens, and position.x will become 200 in 1 second (for example, 1000ms).

You can also use the onUpdate callback function to print the results to the console


tween.onUpdate(function() {
  console.log(this.x);
});

This function is called every time the tweens are updated. Its frequency depends on many factors. For example: depends on the running speed of your computer or device

Start animation

Tween.js itself will not run and needs to be explicitly told through the update method When will it start running? It is recommended to use this method in the animation main loop. You can obtain good image performance by calling the requestAnimationFrame method


animate();
 
function animate() {
  requestAnimationFrame(animate);
  // [...]
  TWEEN.update();
  // [...]
}

The parameterless calling method is used here, and the update method will clarify the current time in order to obtain the execution time of the last animation .

You can also specify a time for the update method:


TWEEN.update(100);

The above statement means: update time = 100 milliseconds. You can use this approach to identify all time-varying functions in your code. For example, if the animation has started and you want all animations to proceed simultaneously, change the animate code to this:


##

var currentTime = player.currentTime;
TWEEN.update(currentTime);

Control animation

[start and stop]

Tween.start and Tween.stop are used to control the start and end of the tween animation respectively

For animations that have ended and have not started, the Tween.stop method does not kick in. The Tween.start method also receives a time parameter. If this parameter is used, the tween animation will start animation after delaying this number of times. Otherwise it will start the animation immediately

[update]

You can use the TWEEN.update method to perform animation updates

[chain]

If you make Multiple lines, for example: one animation starts after another animation ends. This can be achieved through the chain method. In the following code, tweenB starts animation after tweenA


tweenA.chain(tweenB);

You can create an infinite loop animation like the following:


tweenA.chain(tweenB);
tweenB.chain(tweenA);

[repeat]

If you make a loop animation, you can use chain to achieve it, but a better way is to use the repeat method. It receives a parameter describing how many times it wants to loop


tween.repeat(10); // repeats 10 times and stops
tween.repeat(Infinity); // repeats forever

[yoyo]

This function only works when using the repeat method. When it is activated, the tween's effect is similar to a yoyo ball effect. The effect is that the animation will bounce in the opposite direction at the beginning or end

[delay]

The delay method is used to control the delay between animations


tween.delay(1000);
tween.start();

Global methods

The following methods are defined in the global object of TWEEN, most of which are not used, except the update method:

[TWEEN.update(time)]

This method is used for all activated tweens. If time is not specified, the current time will be used.

[TWEEN.getAll and TWEEN.removeAll]

These two methods are used to obtain a reference to the activated tweens array, or to remove all tweens from the array.

[TWEEN.add(tween) and TWEEN.remove(tween)]

Used to add a tween to the activated tweens, or remove a tween

easing function

tween.js provides some available easing functions. Available functions are: Linear, Quadratic, Cubic, Quartic, Quintic, Sinusoidal, Exponential, Circular, Elastic, Back and Bounce. The easing types are divided into: In, Out and InOut

Not only can you use the easing function provided by tween.js, you can also customize the easing function. But the following rules must be followed

1. It must receive a parameter

2. It must return a value based on the input parameter

The easing function is only used every time on each tween Called when updated, regardless of how many properties have been changed. The result is then used for the initial value


easedElapsed = easing(k);
for each property:
  newPropertyValue = initialPropertyValue + propertyDelta * easedElapsed;

下面是一个使用Math.floor来做easing效果的例子:


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

可以在tween 这样使用它


tween.easing(tenStepEasing);

回调函数

另外一个有用的特性是可以在每次tween循环周期的指定时间点调用自定义的函数。

例如:假设想使一些不能直接修改参数的对象执行动画,要访问该对象的参数只能通过setter方法,可以通过update方法的回调函数来设置新的setter值


var trickyObjTween = new TWEEN.Tween({
  propertyA: trickyObj.getPropertyA(),
  propertyB: trickyObj.getPropertyB()
})
  .to({ propertyA: 100, propertyB: 200 })
  .onUpdate(function() {
    this.setA( this.propertyA );
    this.setB( this.propertyB );
  });

或者如果想确认tween动画开始后某个对象指定状态下的某个值,可以通过start回调来获取它:


var tween = new TWEEN.Tween(obj)
  .to({ x: 100 })
  .onStart(function() {
    this.x = 0;
  });

【onStart】

tween开始动画前的回调函数。

【onStop】

tween结束动画后的回调函数。

【onUpdate】

在tween每次被更新后执行。

【onComplete】

在tween动画全部结束后执行。

The above is the detailed content of Detailed explanation of usage examples of tween.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor