Home Web Front-end JS Tutorial Detailed introduction to Tween.js animation

Detailed introduction to Tween.js animation

Jun 26, 2017 pm 01:34 PM
javascript animation Effect

1. Usage of apply, and call.

Let’s start with something unrelated to this blog post, which is the usage of apply and call. In fact, the usage of apply and call are the same, but their parameters are different. apply is an array, while call is passed individually, similar to an enumeration.

1. Liezi converts arguments into a standard array, and you can use push and other methods.

function test(){//arguments.push(5); //arguments.push is not a function    console.log(arguments)var arg = Array.prototype.slice.apply(arguments,[]);   // var arg = Array.prototype.slice.call(arguments,'');console.log(arg); //[1,2,3,4]arg.push(5); // [1,2,3,4,5]}

test(1,2,3,4);
Copy after login

2. How to push the parameters in arguments directly into an array? (Also with the help of apply)

function test(){var arg = [];
    Array.prototype.push.apply(arg,arguments);
    console.log(arg); // [1,2,3,4] 是不是发现要把一个数组//插入到另外一个数组的后面不用for循环了,也不用contact了呢?//其实apply 和call还是有多用法,比如继承。其实主要是把//前面对象的方法赋给后面对象而已。比如 object.apply(object1,arg)//把object的方法赋给 object1。而 arg是参数。}

test(1,2,3,4);
Copy after login

The episode ends here. The following mainly explains tween.js

2. About Tween.js

1. Tween.js is a JS resource that contains various classic animation algorithms. Actually more similar to jQuery.easing.js. The main method names are also the same. The code without compression is only 800 lines.

Mainly includes:

  1. Linear: Linear uniform motion effect;

  2. Quadratic: Quadratic easing (t^2);

  3. Cubic: Cubic easing Movement (t^3);

  4. Quartic: Ease movement to the fourth power (t^4);

  5. Quintic: The easing of the fifth power (t^5);

  6. Sinusoidal: The easing of the sinusoidal curve (sin(t ));

  7. Exponential: Easing of exponential curve (2^t);

  8. ##Circular : Circular curve easing (sqrt(1-t^2));

  9. Elastic: Exponentially decaying sinusoidal curve easing;

  10. Back: Cubic easing beyond range ((s+1)*t^3 – s*t^2);

  11. Bounce: Exponentially decaying bounce easing.

Each effect is divided into three easing modes, which are:

  • easeIn: Accelerate from 0 Easing, that is, slow first and then fast;

  • easeOut: Easing to 0, that is, fast first and then slow;

  • easeInOut: Easing starts from 0 in the first half and decelerates to 0 in the second half.

Many friends

easeIn and easeOut I can’t remember which one is faster or which one is slower. I will teach you again here. A unique evil notation. Think about our first OOXX. When we went in (easeIn), we were slow at first, then fast when we got in; and then we came out (easeOut ), it starts quickly, and then slows down as it almost comes out and is reluctant to leave. It completely matches the animation effect we have here.

All these easing algorithms are inseparable from the following four parameters,

t, b, c, d, The meaning is as follows

/*
 * t: current time(当前时间);
 * b: beginning value(初始值);
 * c: change in value(变化量);
 * d: duration(持续时间)。 */
Copy after login
2.console.log(TWEEN);

console.log(TWEEN)
Copy after login

It can be seen in There are many methods and objects mounted on TWEEN. As long as we dig out one by one, we will know the specific use.

3. Let’s start with a small example.

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><style>#target{width: 100px;height: 100px;background: red;}</style></head><body><div id="target"></div></body><script src="tween.js?1.1.11"></script><script src="index.js?1.1.11"></script></html>
Copy after login
var position;var target;var tween, tweenBack;

init();
animate();function init() {

    position = {x: 100, y: 100, rotation: 0};
    target = document.getElementById('target');
    tween = new TWEEN.Tween(position)
      .to({x: 700, y: 200, rotation: 359}, 2000)
      .delay(1000)
      .easing(TWEEN.Easing.Elastic.InOut)
      .onUpdate(update);

    tweenBack = new TWEEN.Tween(position)
      .to({x: 100, y: 100, rotation: 0}, 3000)
      .easing(TWEEN.Easing.Elastic.InOut)
      .onUpdate(update);

    tween.chain(tweenBack);
    tweenBack.chain(tween);

    tween.start();

}function animate( time ) {

    requestAnimationFrame( animate );

    TWEEN.update( time );

}function update() {

    target.style.webkitTransform = 'translate('+position.x+ 'px'+','+ position.y + 'px' +')' + 'rotate(' + Math.floor(position.rotation) + 'deg)';//target.style.webkitTransform = 'rotate(' + Math.floor(position.rotation) + 'deg)';
   // target.style.MozTransform = 'rotate(' + Math.floor(position.rotation) + 'deg)';}
Copy after login

Each api corresponds to the source code to trace. Just know how to use it. Comparing the source code is just over 800 lines.

4. Motion function

(function() {var lastTime = 0;var vendors = ['ms', 'moz', 'webkit', 'o'];for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    } if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {var currTime = new Date().getTime();var timeToCall = Math.max(0, 16 - (currTime - lastTime));var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;return id;
        }; if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());
Copy after login
5. Conclusion.

There are many small roads, detours, big roads, and bumpy mud roads in a person's life. Anyway, my hometown is full of bumpy mud roads. It has been almost 6 years since I came into contact with the first website. Time flies so fast, and the trajectory of life changes quickly. If you want to find a bright road out of the bumpy mud road, you must move forward without any intention of retreating. How far you can go in a field depends on how long you can persist. Some people say that when you have persisted in a field for 10,000 hours, you are a master in this field. 10000/24? It seems to be more than 400 days. Excluding sleeping time, work time, and game time. It is estimated that it will take 4-6 years to reach 10,000 hours. I also wish you all a happy day and everything goes well.

The above is the detailed content of Detailed introduction to Tween.js animation. 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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Users encounter rare glitches: Samsung Watch smartwatches suddenly experience white screen issues Users encounter rare glitches: Samsung Watch smartwatches suddenly experience white screen issues Apr 03, 2024 am 08:13 AM

You may have encountered the problem of green lines appearing on the screen of your smartphone. Even if you have never seen it, you must have seen related pictures on the Internet. So, have you ever encountered a situation where the smart watch screen turns white? On April 2, CNMO learned from foreign media that a Reddit user shared a picture on the social platform, showing the screen of the Samsung Watch series smart watches turning white. The user wrote: "I was charging when I left, and when I came back, it was like this. I tried to restart, but the screen was still like this during the restart process." Samsung Watch smart watch screen turned white. The Reddit user did not specify the smart watch. Specific model. However, judging from the picture, it should be Samsung Watch5. Previously, another Reddit user also reported

Animation not working in PowerPoint [Fixed] Animation not working in PowerPoint [Fixed] Feb 19, 2024 am 11:12 AM

Are you trying to create a presentation but can't add animation? If animations are not working in PowerPoint on your Windows PC, then this article will help you. This is a common problem that many people complain about. For example, animations may stop working during presentations in Microsoft Teams or during screen recordings. In this guide, we will explore various troubleshooting techniques to help you fix animations not working in PowerPoint on Windows. Why aren't my PowerPoint animations working? We have noticed that some possible reasons that may cause the animation in PowerPoint not working issue on Windows are as follows: Due to personal

Kyushu Fengshen Assassin 4S Radiator Review Air-cooled 'Assassin Master' Style Kyushu Fengshen Assassin 4S Radiator Review Air-cooled 'Assassin Master' Style Mar 28, 2024 am 11:11 AM

Speaking of ASSASSIN, I believe players will definitely think of the master assassins in "Assassin's Creed". They are not only skilled, but also have the creed of "devoting themselves to the darkness and serving the light". The ASSASSIN series of flagship air-cooled radiators from the appliance brand DeepCool coincide with each other. Recently, the latest product of this series, ASSASSIN4S, has been launched. "Assassin in Suit, Advanced" brings a new air-cooling experience to advanced players. The appearance is full of details. The Assassin 4S radiator adopts a double tower structure + a single fan built-in design. The outside is covered with a cube-shaped fairing, which has a strong overall sense. It is available in white and black colors to meet different colors. Tie

How to set up ppt animation to enter first and then exit How to set up ppt animation to enter first and then exit Mar 20, 2024 am 09:30 AM

We often use ppt in our daily work, so are you familiar with every operating function in ppt? For example: How to set animation effects in ppt, how to set switching effects, and what is the effect duration of each animation? Can each slide play automatically, enter and then exit the ppt animation, etc. In this issue, I will first share with you the specific steps of entering and then exiting the ppt animation. It is below. Friends, come and take a look. Look! 1. First, we open ppt on the computer, click outside the text box to select the text box (as shown in the red circle in the figure below). 2. Then, click [Animation] in the menu bar and select the [Erase] effect (as shown in the red circle in the figure). 3. Next, click [

After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 Jan 26, 2024 am 09:42 AM

This website reported on January 26 that the domestic 3D animated film "Er Lang Shen: The Deep Sea Dragon" released a set of latest stills and officially announced that it will be released on July 13. It is understood that "Er Lang Shen: The Deep Sea Dragon" is produced by Mihuxing (Beijing) Animation Co., Ltd., Horgos Zhonghe Qiancheng Film Co., Ltd., Zhejiang Hengdian Film Co., Ltd., Zhejiang Gongying Film Co., Ltd., Chengdu The animated film produced by Tianhuo Technology Co., Ltd. and Huawen Image (Beijing) Film Co., Ltd. and directed by Wang Jun was originally scheduled to be released in mainland China on July 22, 2022. Synopsis of the plot of this site: After the Battle of the Conferred Gods, Jiang Ziya took the "Conferred Gods List" to divide the gods, and then the Conferred Gods List was sealed by the Heavenly Court under the deep sea of ​​Kyushu Secret Realm. In fact, in addition to conferring divine positions, there are also many powerful evil spirits sealed in the Conferred Gods List.

Exquisite light and shadow art in spring, Haqu H2 is the cost-effective choice Exquisite light and shadow art in spring, Haqu H2 is the cost-effective choice Apr 17, 2024 pm 05:07 PM

With the arrival of spring, everything revives and everything is full of vitality and vitality. In this beautiful season, how to add a touch of color to your home life? Haqu H2 projector, with its exquisite design and super cost-effectiveness, has become an indispensable beauty in this spring. This H2 projector is compact yet stylish. Whether placed on the TV cabinet in the living room or next to the bedside table in the bedroom, it can become a beautiful landscape. Its body is made of milky white matte texture. This design not only makes the projector look more advanced, but also increases the comfort of the touch. The beige leather-like material adds a touch of warmth and elegance to the overall appearance. This combination of colors and materials not only conforms to the aesthetic trend of modern homes, but also can be integrated into

Huntkey MX750P full module power supply review: 750W of concentrated platinum strength Huntkey MX750P full module power supply review: 750W of concentrated platinum strength Mar 28, 2024 pm 03:20 PM

With its compact size, the ITX platform has attracted many players who pursue the ultimate and unique beauty. With the improvement of manufacturing processes and technological advancements, both Intel's 14th generation Core and RTX40 series graphics cards can exert their strength on the ITX platform, and gamers also There are higher requirements for SFX power supply. Game enthusiast Huntkey has launched a new MX series power supply. In the ITX platform that meets high-performance requirements, the MX750P full-module power supply has a rated power of up to 750W and has passed 80PLUS platinum level certification. Below we bring the evaluation of this power supply. Huntkey MX750P full-module power supply adopts a simple and fashionable design concept. There are two black and white models for players to choose from. Both use matte surface treatment and have a good texture with silver gray and red fonts.

Easily understand 4K HD images! This large multi-modal model automatically analyzes the content of web posters, making it very convenient for workers. Easily understand 4K HD images! This large multi-modal model automatically analyzes the content of web posters, making it very convenient for workers. Apr 23, 2024 am 08:04 AM

A large model that can automatically analyze the content of PDFs, web pages, posters, and Excel charts is not too convenient for workers. The InternLM-XComposer2-4KHD (abbreviated as IXC2-4KHD) model proposed by Shanghai AILab, the Chinese University of Hong Kong and other research institutions makes this a reality. Compared with other multi-modal large models that have a resolution limit of no more than 1500x1500, this work increases the maximum input image of multi-modal large models to more than 4K (3840x1600) resolution, and supports any aspect ratio and 336 pixels to 4K Dynamic resolution changes. Three days after its release, the model topped the HuggingFace visual question answering model popularity list. Easy to handle

See all articles