Home Web Front-end JS Tutorial Detailed explanation of usage examples of tween.js

Detailed explanation of usage examples of tween.js

Sep 16, 2017 am 09:36 AM
javascript Detailed 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 }
Copy after login

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);
Copy after login

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


// And set it to start
tween.start();
Copy after login

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();
  // [...]
}
Copy after login
Copy after login

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);
});
Copy after login

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();
  // [...]
}
Copy after login
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

You can create an infinite loop animation like the following:


tweenA.chain(tweenB);
tweenB.chain(tweenA);
Copy after login

[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
Copy after login

[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();
Copy after login

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;
Copy after login

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


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

可以在tween 这样使用它


tween.easing(tenStepEasing);
Copy after login

回调函数

另外一个有用的特性是可以在每次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 );
  });
Copy after login

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


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

【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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Starting from Scratch: Detailed Installation and Setup of VNC on Ubuntu Starting from Scratch: Detailed Installation and Setup of VNC on Ubuntu Dec 29, 2023 pm 04:27 PM

Starting from scratch: Detailed explanation of the installation and settings of VNC on Ubuntu On the Ubuntu operating system, VNC (Virtual Network Computing) is a remote desktop protocol that enables remote access and control of the Ubuntu desktop through a network connection. This article will detail the steps to install and set up VNC on Ubuntu, including specific code examples. Step 1: Install the VNC server. Open the terminal and enter the following command to update the software source and install the VNC server: sud

See all articles