Giter Site home page Giter Site logo

Tweening arrays and objects? about tween.js HOT 5 CLOSED

tweenjs avatar tweenjs commented on May 17, 2024
Tweening arrays and objects?

from tween.js.

Comments (5)

sole avatar sole commented on May 17, 2024

WOW. Now that is massive! 😱

The reason tween.js is fast is because it's simple at its core. If we add all these checks to be executed per frame, it will slow down. I think a solution for tweening complicated objects could be to "flatten" the properties you want to tween, and create a similarly flat object for the "to" values. The onUpdate function should take care of updating the original object with the values from the tween, and that way you'd have only ONE tween which means only ONE easing function would be calculated, not one per nested / complicated property.

I know this is something that needs to be done somehow often when you try to animate complex objects, so I wouldn't be against it per se, but definitely would try to go the external function that preprocesses and creates an onUpdate function route rather than modifying the tween.js core.

from tween.js.

sole avatar sole commented on May 17, 2024

Also, there is support for tweening array values already: http://sole.github.io/tween.js/examples/06_array_interpolation.html

from tween.js.

mrdoob avatar mrdoob commented on May 17, 2024

I agree. If anything something like TweenGroup could be something to consider.

from tween.js.

earthling4211573 avatar earthling4211573 commented on May 17, 2024

I've rewritten the code using the "flatten" method and a single tween instead of multiple, and it's got support for nesting! Aswell as colors (depends on tinycolors), which is a bit convoluted though to make sure it doesn't change hsv to hex, just hex to hsv and back to hex:

http://jsfiddle.net/gautamadude/engDj/

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

//Flatten/Deflate an object
var flatten = function(source,pathArray,result){
    pathArray = (typeof pathArray === 'undefined') ? [] : pathArray;
    result = (typeof result === 'undefined') ? {} : result;
    var key, value, newKey;
    for (var i in source) { 
        if (source.hasOwnProperty(i)) {
            key                 = i;
            value               = source[i];
            pathArray.push(key);

            if (typeof value === 'object' && value !== null){
                result          = flatten(value,pathArray,result);
            } else {
                newKey          = pathArray.join('.');
                result[newKey]  = value;
            }
            pathArray.pop();
        }
    }
    return result;
};

function ref(obj, str) {
    return str.split(".").reduce(function(o, x) { return o[x] }, obj);
}

//Move values from a flatten object to its original object
function returnValue(obj, flattened, key) {
    parts = key.split(/\.(?=[^.]+$)/)  // Split "foo.bar.baz" into ["foo.bar", "baz"]
    if (parts.length == 1) {
        obj[parts[0]] = flattened[key];
    } else {
        ref(obj, parts[0])[parts[1]] = flattened[key];
    }
}

//Convert hex to ahsv and save the keys or places
//where the original hex was
function toAhsv(obj, key, color_keys) {
    if (typeof obj[key] == "string") {
        if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(obj[key])) {
            var t = tinycolor(obj[key])
            var hsv = t.toHsv();
            delete obj[key];
            obj[key+".a"] = hsv.a;
            obj[key+".h"] = hsv.h;
            obj[key+".s"] = hsv.s;
            obj[key+".v"] = hsv.v;
            if (color_keys != undefined) color_keys[key] = {};
        }                         
    }
}

var flattened_from = flatten(from);
var flattened_to = flatten(to);
var color_keys = {};
for (key in flattened_from) {
    toAhsv(flattened_from, key, color_keys);
}
for (key in flattened_to) {
    toAhsv(flattened_to, key);
}

new TWEEN.Tween( flattened_from )
    .to( flattened_to, 2000 )
    .easing( TWEEN.Easing.Linear.None )
    .onUpdate( function() {
        //Convert ahsv to hex and set it in the this
        //object under a key that refers to the colors
        //place in the original object.
        for (key in color_keys) {
            var ahsv = {};
            ahsv.a = this[key+".a"];
            ahsv.h = this[key+".h"];
            ahsv.s = this[key+".s"];
            ahsv.v = this[key+".v"];
            this[key] = tinycolor(ahsv).toHexString();
        }
        //Move the values from the flattened and tweening object
        //to the original object
        for (key in this) {
            returnValue(from, this, key);
        }
    })
    .onComplete( function () {
        console.log(from) // Everything tweened correctly!
    }).start();

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

Uses code snippets from:
http://stackoverflow.com/questions/10934664/convert-string-in-dot-notation-to-get-the-object-reference
https://gist.github.com/wmbenedetto/5080102

from tween.js.

thednp avatar thednp commented on May 17, 2024

@gautamadude do you have a working example of tweening colors? Would you please share it with us?

from tween.js.

Related Issues (20)

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.