Coder Social home page Coder Social logo

tweenjs / tween.js Goto Github PK

View Code? Open in Web Editor NEW
9.6K 215.0 1.4K 16.6 MB

JavaScript/TypeScript animation engine

Home Page: https://tweenjs.github.io/tween.js/

License: Other

CSS 0.30% HTML 0.23% JavaScript 40.40% TypeScript 59.08%
tween tweenjs animation javascript typescript easing easing-functions easing-equations interactive interaction easing-curves

tween.js's Introduction

tween.js

JavaScript (TypeScript) tweening engine for easy animations, incorporating optimised Robert Penner's equations.

NPM Version CDNJS NPM Downloads Build and Tests

More languages: English, 简体中文


<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/20.0.0/tween.umd.js"></script>

<div id="box"></div>

<style>
	#box {
		background-color: deeppink;
		width: 100px;
		height: 100px;
	}
</style>

<script>
	const box = document.getElementById('box') // Get the element we want to animate.

	const coords = {x: 0, y: 0} // Start at (0, 0)

	const tween = new TWEEN.Tween(coords, false) // Create a new tween that modifies 'coords'.
		.to({x: 300, y: 200}, 1000) // Move to (300, 200) in 1 second.
		.easing(TWEEN.Easing.Quadratic.InOut) // Use an easing function to make the animation smooth.
		.onUpdate(() => {
			// Called after tween.js updates 'coords'.
			// Move 'box' to the position described by 'coords' with a CSS translation.
			box.style.setProperty('transform', 'translate(' + coords.x + 'px, ' + coords.y + 'px)')
		})
		.start() // Start the tween immediately.

	// Setup the animation loop.
	function animate(time) {
		tween.update(time)
		requestAnimationFrame(animate)
	}
	requestAnimationFrame(animate)
</script>

Try this example on CodePen

Installation

From CDN

Install from a content-delivery network (CDN) like in the above example.

From cdnjs:

<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/20.0.0/tween.umd.js"></script>

Or from unpkg.com:

<script src="https://unpkg.com/@tweenjs/tween.js@^20.0.0/dist/tween.umd.js"></script>

Note that unpkg.com supports a semver version in the URL, where the ^ in the URL tells unpkg to give you the latest version 20.x.x.

Build and include in your project with script tag

Currently npm is required to build the project.

git clone https://github.com/tweenjs/tween.js
cd tween.js
npm install
npm run build

This will create some builds in the dist directory. There are currently two different builds of the library:

  • UMD : tween.umd.js
  • ES6 Module : tween.es.js

You are now able to copy tween.umd.js into your project, then include it with a script tag, which will add TWEEN to the global scope,

<script src="path/to/tween.umd.js"></script>

or import TWEEN as a JavaScript module,

<script type="module">
	import * as TWEEN from 'path/to/tween.es.js'
</script>

where path/to is replaced with the location where you placed the file.

With npm install and import from node_modules

You can add tween.js as an npm dependency:

npm install @tweenjs/tween.js

With a build tool

If you are using Node.js, Parcel, Webpack, Rollup, Vite, or another build tool, then you can now use the following to include tween.js:

import * as TWEEN from '@tweenjs/tween.js'

Without a build tool

You can import from node_modules if you serve node_modules as part of your website, using an importmap script tag. First, assuming node_modules is at the root of your website, you can write an import map:

<script type="importmap">
	{
		"imports": {
			"@tweenjs/tween.js": "/node_modules/@tweenjs/tween.js/dist/tween.es.js"
		}
	}
</script>

Now in any of your module scripts you can import it by its package name:

import * as TWEEN from '@tweenjs/tween.js'

Features

  • Does one thing and one thing only: tween properties
  • Doesn't take care of CSS units (e.g. appending px)
  • Doesn't interpolate colors
  • Easing functions are reusable outside of Tween
  • Can also use custom easing functions

Documentation

Examples

hello world hello world
(source)
Bars Bars
(source)
Black and red Black and red
(source)
Graphs Graphs
(source)
Simplest possible example Simplest possible example
(source)
Video and time Video and time
(source)
Array interpolation Array interpolation
(source)
Dynamic to, object Dynamic to, object
(source)
Dynamic to, interpolation array Dynamic to, interpolation array
(source)
Dynamic to, large interpolation array Dynamic to, large interpolation array
(source)
Repeat Repeat
(source)
Relative values Relative values
(source)
Yoyo Yoyo
(source)
Stop all chained tweens Stop all chained tweens
(source)
Custom functions Custom functions
(source)
Relative start time Relative start time
(source)
Pause tween Pause tween
(source)
Complex properties Complex properties
(source)
Animate an array of values Animate an array of values
(source)

Tests

You need to install npm first--this comes with node.js, so install that one first. Then, cd to tween.js's (or wherever you cloned the repo) directory and run:

npm install

To run the tests run:

npm test

If you want to add any feature or change existing features, you must run the tests to make sure you didn't break anything else. Any pull request (PR) needs to have updated passing tests for feature changes (or new passing tests for new features or fixes) in src/tests.ts a PR to be accepted. See contributing for more information.

People

Maintainers: Joe Pea (@trusktr).

All contributors.

Projects using tween.js

Lume A-Frame VR MOMA Inventing Abstraction 1910-1925 Web Lab MACCHINA I Minesweeper 3D ROME WebGL Globe Androidify The Wilderness Downtown Linechart

tween.js's People

Contributors

alexburner avatar amilajack avatar azachar avatar benjamind avatar chepe263 avatar christjt avatar dalisoft avatar deanm avatar egraether avatar endel avatar fundon avatar hendrysadrak avatar iangilman avatar lechecacharro avatar malows avatar masatomakino avatar mikebolt avatar mrdoob avatar nidorx avatar olizilla avatar remcokranenburg avatar robertodeveloper avatar siwel avatar sole avatar talltyler avatar tdreyno avatar tobyspark avatar trusktr avatar tvytlx avatar weiserhei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tween.js's Issues

Problem with autostop (seems to be a scope issue)

Hi,

I just tried Tween.js, and used TWEEN.setAutostart(true), and it killed all my following jQuery.ajax calls.

I took a look at the sources, and it looks like the this.stop() call in TWEEN.update (line 108) does actually not call TWEEN.stop(), but window.stop() (which kills the loading processes), since the method is called through window.setInterval (line 30).

Regards,

Alexis

Problem when try to tween mesh/object in a model

I've tried to tween a object or mesh in a collada model, but it didn't tween as expected. Instead, some of selected objects showed up instantly in origin, while some of them just didn't move. Any help would be appreciated.

TWEEN.start is not a function

In the example script under 'Usage' you call TWEEN.start(), but there doesn't appear to be any such method, as if i call it i get an error? Having checked the class, no such method appears to exist?

Having looked at all the examples, am i correct in thinking that this tween engine actually has a dependency on RequestAnimationFrame.js (or some other bespoke method to get the tweens to actually update), as i've tried setting up a tween with an onUpdate callback, but after calling start() nothing appears to happen?

create an continousliy repeating tween

I used the TWEEN.to function to rotate an object. But after completion I always had to reset the rotation axis to 0 and than again call TWEEN.to to rotate 360 degress again.

So I added a TWEEN.mod function, with looks like this:

this.mod = function ( properties, duration ) {

    if( duration !== null ) {

        _duration = duration;

    }

    for ( var property in properties ) {

        // This prevents the engine from interpolating null values
        if ( _object[ property ] === null ) {

            continue;

        }

        // set teh objects properties to its "zero value" with modulo
        _object[ property ] %= properties[ property ];

        // The current values are read when the tween starts;
        // here we only store the final desired values
        _valuesEnd[ property ] = properties[ property ];

    }

    return this;

};

As you can see I just changed the .to function. And setting the objects Property to its modulo value (which automaticly resets it to zero).

The function still has to be called after completion but without reseting the objects properties.

This could definetly get improved.

work with .stop() and start() calls too.

Hope this helps.

example:

rotate: function() {
            sulzer3D.tween_rot = new TWEEN.Tween( sulzer3D.group.rotation ).mod( {
                y: 2 * Math.PI }, 6000 )
            .onComplete(sulzer3D.rotate).start();
}

this example will loop always n%2PI - 0 .. <2PI

Implement .repeat

As mentioned in #64.

I'm creating the issue because it'll be a sort of experimental feature so any comments will get grouped here instead of hanging from individual commits.

Breaking the chain of tweens

When I stop a circular chain of tweens i.e. forward/backward, I would like my object to resume its original position back. This means, if it's coming forward, it finished the forward and goes backward and stops or if it's going backwards it finishes its backward tween and stops. Something like backwardsTween.breakChain(). Can I do this with tween.js ? Does it sound like a useful feature ?

Custom Easing Functions

I was looking at implementing Tween.js (r5) but ran across one stumbling block.

I have a couple of custom easing functions I've created using Tim Groleau's easing generator (http://www.timotheegroleau.com/Flash/experiments/easing_function_generator.htm), but I cannot figure out how to convert those functions to match the easing functions used in Tween.js.

In both cases, you each cite Robert Penner's formulas, but as far as I can tell his formulas take four or more arguments, whereas yours takes only one.

Update

I was able to get the custom easing functions working by doing the following:

  1. Create a new js file. In my case is called it: Tween.custom.js
  2. At the top of the file add the following, where "myCustom" is replaced with whatever name you like:
TWEEN.Easing.myCustom = {};
  1. Paste in your custom easing function, which looks something like this:
function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(-0.349999999999998*tc*ts + 1.4*ts*ts + -1.1*tc + -1.6*ts + 2.65*t);
}
  1. And update it to look like this, where "myEasingOut" is whatever name you want to give your easing:
TWEEN.Easing.myCustom.myEasingOut = function( k ) {
    var t = (k*100); // add this
    var d = 100; // add this

    var ts=(t/=d)*t;
    var tc=ts*t;
    return (-0.349999999999998*tc*ts + 1.4*ts*ts + -1.1*tc + -1.6*ts + 2.65*t); // remove "b+c*"
};
  1. Include your new file after the Tween.js file:
<script src="js/Tween.js"></script>
<script src="js/Tween.custom.js"></script>
  1. Call your easing function as you would any of the native easing functions:
... .easing( TWEEN.Easing.myCustom.myEasingOut );

If you want to learn more about how easing works, here is an excellent resource: http://upshots.org/actionscript/jsas-understanding-easing

[Suggestion] don't use _tweens.splice( i, 1 )

the order of tweens (in the _tween in TWEEN) is not important.

So , use

            for (var i = numTweens - 1; i >= 0; i--) {
                if ( !_tweens[ i ].update( time ) ) {
                    numTweens--;
                    _tweens[i] = _tweens[numTweens];
                }
            }
            _tweens.length = numTweens;

repleaces

            while ( i < numTweens ) {

                if ( _tweens[ i ].update( time ) ) {

                    i ++;

                } else {

                    _tweens.splice( i, 1 );

                    numTweens --;

                }

            }

MAY BE have a better performance.

to() valuesEnd being static after .start()

I would like to()/valuesEnd to be dynamic. i need it for an animation im doing.

from my understanding after looking at the source. please correct me if im wrong

only the from() is dynamic, correct ?

the to() is set once and for all after the start(), correct ?

the _valueDelta is just a precomputation of valueEnd - valueStart, correct ?

i would be ok to write the patch

Jerome

simpler naming for easing functions

There is one thing that annoys me about TWEEN and I want to collect some opinions:

tween.easing( TWEEN.Easing.Quadratic.EaseIn );

I constantly fail at writing this line correctly. It contains 3 times the phrase 'ease' and I think this is unnecessary. I tried to improve it and this is my best solution:

tween.easing( TWEEN.Quadratic.In );

You can see the necessary changes to the source file here: egraether@733089c

There is only a small downside of this approach. At Line 125 the declaration of the containers looks a little incomprehensible, so I added a comment:
https://github.com/egraether/tween.js/blob/733089c1105b72d43ab90d9f32df80edf5fa86fa/src/Tween.js#L125

Are you happy with how it is, or do you think there is room for improvement?

How stop some chains?

example:

a.chain(b);
b.chain(a);
a.start();

Now, I want stop the a animation, I used

a.stop();

But don't stop a & b. So I used the other way

a.chain();
b.chain();
a.stop();
b.stop();

Can support a simple stop API?

Tween.chain() should return this

  • currently tween.chain doesnt return this
  • so it break the chained api
    new TWEEN.Tween(object3d.scale).to({x: 1.5}, 300)
                .chain(othertween)
               .start();

but currently impossible as .start() will create an error

Ability to pause and play

Actuallay I needed such a function for my project. So I decided to add such functionality.

Hope this is usefull. Maybe it could get improved, for example with progressbar. Rewind, fast forward functions an so on. Just an idea

//global vars
_paused = false,
_pasueStart = null,

...

    this.pause = function () {
        if(_paused)
            return;

        _paused = true;
        _pauseStart = new Date().getTime();

        TWEEN.remove( this );
    };

    this.play = function () {
        if(!_paused)
            return;

        _paused = false;

        now = new Date().getTime();

        _startTime += now - _pauseStart;

        TWEEN.add( this );
    };

Broken in IE < 9

...but only because Date.now() is unavailable in IEs prior to 9. The fix is quite simple, however. Something like the following will work just fine:

if (!Date.now) {
  Date.now = function() {
    return new Date().valueOf();
  }
}

Ability to scrub time back and forth

Would be nice to support time moving backwards, useful for when controlling tweens with a time slider (scrubber) widget.

At the moment tween.js only seems to support time moving forwards..perhaps with the way it manages chaining etc. this is not practical?

Group chains

Quick question:
I have an array of objects that I want to tween.
They all need to be tweened simultaneously and execute only 1 oncomplete call when all of them are done.
I could chain them all together, but than it won't be simultaneously.
I tried using a negative delay but that didn't work.

Am I overlooking a feature, or is this just not possible.
Thanks :)

Avoiding prototype values?

Thanks for creating TWEENjs, it is fantastically useful! I've been using TWEENjs to do some THREE property tweening, and I noticed that while tweening the target object's properties are copied all the way up the prototype chain. Is this intended?

I ask because I was going between three ways of tweening properties, for example scale:
a. Write an update function that caters to the specific properties and copies the values passed to "to()"... i.e. onUpdate scale.x = from.x, scale.y = from.y... but this is very clunky and not very dynamic.
b. Pass the scale vector as the from object and a generic object as the target object, i.e. { x: 3, y: 3, z: 3 }... but this is also not very dynamic.
c. Pass the scale vector as the from object and another scale vector as the target object.

Option c seems ideal to me, but the problem is TWEENjs is trying to tween all the target object's prototype properties. I'm not sure why you'd want to tween prototype properties, as that seems to go against the concept of prototyping, so what about the following:

this.start = function ( time ) {

    ...

    for ( var property in _valuesEnd ) {

        // This prevents the engine from interpolating null values
        if ( _valuesEnd.hasOwnProperty( property ) !== true || _object[ property ] === null ) {

            continue;

        }

        ...

    }

};

Alternatively, has using an object's "Keys" method been considered to speed up the Start iteration? See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys. This would avoid the above issue entirely, but also may not have the level of browser support you all are looking for.

Infinite Tween/Interpolation

Is it possible to create a Tween via Tween.js that will infinitely try to keep two values in sync/close together.

Aka lets say we have two objects starting at:
A: (0, 0, 0)
B: (0, 0, 0)
And we want A to always tween to B

Now with the time line:
1 B (3, 0, 0) => A Starts Tween to (3, 0, 0) => A Now (2, 0, 0)
2 B (10, 5, 0) => A Adjusts Tween to (10, 5, 0) => A Now (6, 2, 0)
3 B (10, 5, 0) => A continues Tween => A Now (9, 5, 0)
4 B (10, 5, 0) => A continues Tween => A now (10, 5, 0)
5 B (10, 5, 0) => A does nothing because values haven't changed.

Is this possible?

Tweening arrays and objects?

So I have these "from" and "to" objects that I need to tween:

var from = {x: 0, y: {a: 0, b: 0}, z:[0, 0], color: "#000000"};
var to = {x: 10, y: {a: 20, b: 30}, z:[40, 50], color: "#ffffff"};

Tween.js doesn't handle the "y", "z" or "color" values out of the box, but would it make sense to do so? Maybe not colors, but what about objects and arrays? And perhaps even nested objects and arrays like so:

{x: 0, y: {a: {t: 0, k:0}, b: 0}, z:[[5,2], [10]], color: "#000000"};

So far to deal with this I came up with the following in a hurry, and I still need to implement support for nested arrays and objects (also if you know of a better way I'd be interested):

http://jsfiddle.net/gautamadude/YRbQ3/

var from = {x: 0, y: {a: 0, b: 0}, z:[0, 0], color: "#000000"};
var to = {x: 10, y: {a: 20, b: 30}, z:[40, 50], color: "#ffffff"};
var speed = 2000;
var easing = TWEEN.Easing.Linear.None;
var delay = 0;
tweenWithObjectArrayAndColorSupport(from, to, speed, easing, delay);

function tweenWithObjectArrayAndColorSupport(from, to, speed, easing, delay) {
    var outFromTo = tweenSeperate(from, to); //Seperate the colors, array objects, and objects
                                             //from the "from" and "to" objects.

    //Tween the remainder
    new TWEEN.Tween( from )
        .to( to, speed )
        .easing( easing )
        .delay(delay)
        .start();

    //Create Tweens for the separated values
    for (type in outFromTo.from) {
        for (attr in outFromTo.from[type]) {
            var vals = {"attr": attr, "type": type};
            createTween(vals, outFromTo.from[type][attr], outFromTo.to[type][attr], speed, easing, delay);
        }
    }
}

function tweenSeperate(from, to) {
    var vals = {};
    var objs = [from, to];
    for (o in objs) {
        var outColors = {};
        var outObjects = {};
        var outArrays = {};
        for (a in objs[o]) {
            if (typeof objs[o][a] == "string") {
                if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(objs[o][a])) {
                    var t = tinycolor(objs[o][a])
                    outColors[a] = t.toHsv();
                    delete objs[o][a];
                }
            }
            if (Object.prototype.toString.call(objs[o][a]) == "[object Object]") {
                outObjects[a] = objs[o][a];
                delete objs[o][a];
            } else if (Object.prototype.toString.call(objs[o][a]) == "[object Array]") {
                outArrays[a] = {};
                var array = objs[o][a];
                delete objs[o][a];
                for (val in array) {
                    outArrays[a][val] = array[val];
                }
            }
        }
        if (o == "0") vals.from = {"colors": outColors, "objects": outObjects, "arrays": outArrays};
        else vals.to = {"colors": outColors, "objects": outObjects, "arrays": outArrays};
    }
    return vals;
}

function createTween(vals, f, t, speed, easing, delay) {
    new TWEEN.Tween( f )
        .to( t, speed )
        .easing( easing )
        .onUpdate( function() {
            if (vals.type == "objects" && from[vals.attr] == undefined) {
                from[vals.attr] = {};
            } else if (vals.type == "arrays" && from[vals.attr] == undefined) {
                from[vals.attr] = [];
            }

            if (vals.type == "colors") {
                var t = tinycolor(this)
                from[vals.attr] = t.toHexString();
            } else {
                for (a in this) {
                    if (a != "attr" & a != "type") {
                        from[vals.attr][a] = this[a];
                    }
                }
            }
        })
        .onComplete( function () {
            console.log(from); //Everything Tweened correctly!
        })
        .delay(delay)
        .start();
}

function r(frame) {
    requestAnimationFrame( r );
    TWEEN.update();
}
r();

The reason I need this is to tween KineticJS, Two.js and Pixi.js shape attributes.

So basically, would it make sense to implement support for tweening array and object values (nested or not) in Tween.js?

TWEEN and Tween within a javascript "class"

Hey,

Great work on this library — I went through a couple of the demos and wrote a simple test myself and it's really smooth and really fast! I had a question more than an issue, but I didn't know where to ask this and I didn't find an answer in the examples. Anyways, here goes:

How do I tween within a class? Here's pseudo code which results in "No method 'update' found":

Okay this didn't save my spaces. You can check out this gist for tabbed out: https://gist.github.com/660832

Is it possible to tween values relatively?

Supose that I have something like:

var position = new Vec2(50, 50);

And I want to move the thing 10 to the right.

TWEEN.Tween(position, {x: position.x + 10}).start()

On GreenSock's tweening engine for Flash, it's possible to use relative values, declaring the offset as a string, like:

TWEEN.Tween(position, {x: "+10"}).start()

Do you guys have something against this approach?

performance.now()

Now that Chrome is using submillisecond precision for requestAnimationFrame, it'd be great if Tween.js used performance.now() instead of Date.now() when available.

Possibility to FastForward and Rewind

I have two questions cause i'm new to javascript and tween.js

  1. is there the possibility of fastforward and rewind the animation?

  2. how can i stop completely the animation, in order to start again it from the beginning when i play it again?(i'm using threejs)

Greets
David

remove autostart or make it default

I was thinking about the autostart option in the latest version.

Is it really expensive to have the update interval running with no Tweens in the queue?
If so, then autostart should not be an option and used per default.
If not, then autostart should be removed as it only makes the code more complex.

I personally think that it should be removed.

onStart

I think onStart should not get calledon start() but when the tween actually starts. Meaning delay should also be considered.

I did implement that a while ago but thought you didn't add it for a reason. (If you want to have a look) https://github.com/ap-o/tween.js

Cheers
*A

repeat chained tweens

Hello!

My use case is to chain multiple tweens together and have the entire chain repeat. The framework currently only kind of supports this. You can create a circular chain and the animations will trigger themselves repeatedly as expected, but it will only work if you reset the _object to the original values on each iteration. There is logic in there to do this already when using the repeat flag, but not in conjunction with chains.

I'm not exactly sure what the interface would look like. Here is what I've been doing:

this._sprites["small-ring"].add_animation([
  {
    name: "hoverIn",
    fromStateKey: "small",
    toStateKey: "enlarged",
    duration: 100,
    easing: TWEEN.Easing.Quadratic.In
  },
  {
    name: "hoverActiveShrink",
    fromStateKey: "enlarged",
    toStateKey: "less-enlarged",
    duration: hoverActiveAnimationHalfDuration,
    easing: TWEEN.Easing.Cubic.Out
  },
  {
    name: "hoverActiveGrow",
    fromStateKey: "less-enlarged",
    toStateKey: "enlarged",
    duration: hoverActiveAnimationHalfDuration,
    easing: TWEEN.Easing.Cubic.In
  }
], {
  chainNodes: [0, 1, 2, 1]
});

The chainNodes parameter denotes which indexes of the above keyframes should be chained together. So first the hoverIn animation runs, then it bounces back and forth between hoverActiveShrink and hoverActiveGrow.

However this requires that I reset the starting points each time the animations finish:

new TWEEN.Tween(fromProperties)
  .to(toProperties, duration)
  .easing(easing)
  .onUpdate(function () {
    me.set_properties(this);
  })
  .onComplete(function () {
    reset_animation();
  })
  .onStop(function () {
    reset_animation();
  });

You'll notice the onStop callback which I had to add in order to avoid a bug where the animation wouldn't reset if it was stopped before completion. I think the current repeat logic would exhibit this same issue.

variable i conflicting

Hey guys,

Variable i is used in two methods:

TWEEN.remove and TWEEN.update

And it's conflicting between them.

Problem:
in TWEEN.remove``i is used to get the index of the tween:
i = tweens.indexOf( tween );
in TWEEN.update i is used as a counter/index of the tweens array:
tweens[ i ]

At the begining of TWEEN.update i is set to 0.
If after that, TWEEN.remove is called and the Tween doesn't exist yet, i is set to -1.
Which causes tweens[ -1 ] to be undefined and throw an error and not update the tweens properly.

Possible solution:
just use j instead of i in TWEEN.remove to avoid this.

What do you think?

Namespacing completely broken - everything added to window

The TWEEN namespace construction is incorrect - TWEEN == window, and add/remove/update/etc are added to the global scope.
The issue is that in the construct:
var TWEEN = TWEEN || (function() {....})();
'this' inside of the closure is window. You have to fix this up by either doing a (function(){...}).call(TWEEN) or change the construction pattern.

I found this issue when I tried having my own 'update' function which called TWEEN.update:
window.update = function() {
TWEEN.update(); // really window.update(), which causes infinite recursion!
};

[enhancement] Add missing bower.json.

Hey, maintainer(s) of sole/tween.js!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library sole/tween.js is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "sole/tween.js",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Problems creating tween instances inside a different js class file

Hi, I created a Slide.js class file to control the different slides in my application, but the code below (Slide.js) give me an error in Tween.js line 5 Uncaught TypeError: Cannot call method 'call' of undefined

function Slide( id, image ) {
    this.id                 = id;
    this.image              = image;

    this.position           = { x : 0, y : 0, z : 0 };
    this.targetPosition     = { x : 0, y : 0, z : 0 };

    var geometry            = new THREE.PlaneGeometry( 640, 480 );
    var material            = new THREE.MeshBasicMaterial( { color : 0xffffff, map : this.image } );

    this.plane              = new THREE.Mesh( geometry, material );
    this.plane.doubleSided  = true;
    // this.plane.position  = this.position;

    this.tween              = new TWEEN.Tween( this.position )
                                        .to( this.targetPosition, 500 )
                                        .easing( TWEEN.Easing.Elastic.EaseInOut )
                                        .onUpdate( this.updateTween )
                                        .start();

    this.updateTween = function() {
        // this.plane.position.x = this.position.x;
        // this.plane.position.y = this.position.y;
        // this.plane.position.z = this.position.z;
        console.log( this.position.x );
    }

}


Slide.prototype.update = function() {

};

Note: that the Slide.js code gets instantiated in mainApp.js hope this helps

r11 tag is missing

Is r11 finalized, or does the Change log contain work-in-progress? I'm assuming it's finalized since a date is listed. A tag would be helpful.

Possible to force a tween to finish early?

I'm looking for a way to force a tween to jump to its final value prematurely. Peeked at the source by didn't see anything on first glance.

Awesome library btw! Just found it this morning.

Array/Bezier?

A very neat feature from Tweener (http://code.google.com/p/tweener/) was that you could have an array of values in the to()... something like new TWEEN.Tween(this).to({x:[10,20,50]},1000);

That made ridiculously easy to do curve animations. I need to dig in tweener code to see how it was done and which curve were they using though.

Would this be over doing it? Should the curve part be left to the user?

Unable to pass parameters to callbacks

Hi there,
Is it possible to pass parameters to callbacks?

I tried:

.onComplete(myCallback, myParameter1, myParameter2)

which didn't seem to work, and the Tween.js source doesn't seem to indicate any handling of parameters.

I'm probably just doing this wrong :)

Date.now() support.

Yes...we hate old browsers ( < IE8) , but tween.js seems to work perfectly fine with them except for when Date.now() is used.

This is more for if anyone is having issues or if the contributors would like to add something like this in...

Since Date.now() is quicker, we can then provide a simple fallback of some sort:

if (!Date.now) {
  Date.now = function now() {
    return + (new Date);
  };
}

bezier?

Hi I am using the tweenjs for threejs

First: I would like to know if we can do some Tweens using the position and the rotation of the camera at the same time.
something like

new TWEEN.Tween( camera)
.to({position.x: 0,position.y:2710, position.z:9000, rotation.x: -30 * (Math.PI / 180 }, 6000 )
.easing( TWEEN.Easing.Exponential.EaseOut)
.start();

Second: In order to have nice camera movement I would like to know if you some bezier implementation is possible
something like

new TWEEN.Tween(camera)
.to( bezier:[{position.x:0, position.y:0, position.z:50, rotation.x:-30 * (Math.PI / 180)}, 
{position.x:100, position.y:200, position.z:200, rotation.x:-90 * (Math.PI / 180)},
{position.x:200, position.y:300, position.z:100, rotation.x:-60 * (Math.PI / 180)}] )
.orientToBezier(true)
.easing( TWEEN.Easing.Exponential.EaseOut)
.start();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.