Tween.js v3

Dynamic chained animations

by trolleymusic

HTML

<script src="https://raw.github.com/sole/tween.js/master/examples/js/RequestAnimationFrame.js"></script>
<script src="https://raw.github.com/sole/tween.js/master/src/Tween.js"></script>
<div class="box"></div>

CSS

.box {
    width: 100px;
    height: 100px;
    background: pink;
}

JavaScript

var element = document.getElementsByClassName('box')[0];

var update = function (state) {
    console.log(state);
    var trans = "rotate(" + state.rotate + "deg)";
    element.style.webkitTransform = trans;
}

var animate = function () {
    requestAnimationFrame(animate);
    TWEEN.update();
}

var loop = [{
    from : { rotate : 0 },
    to : { rotate : 145 }
},{
    from : { rotate : 145 },
    to : { rotate : 0 }
}];

var tweens = [];

for (var i = 0; i < loop.length; i++) {
    var tween = new TWEEN.Tween(loop[i].from)
        .to(loop[i].to, 4000)
        .onUpdate(function () {
            update(this);
        });
    tweens.push(tween);
    
    if (i > 0) {
        tweens[i-1].chain(tweens[i]);
    }
}

// Hook the last one into the first one				
tweens[tweens.length - 1].chain(tweens[0]);

setTimeout(function () { tweens[0].start() }, 3000);

animate();