原文链接:http://learningthreejs.com/blog/2011/08/17/tweenjs-for-smooth-animation/
本篇介绍的Tween.js是使用tweening engine的非常简单快速的方法。它提供了完全成熟的补间动画。我们开始吧~!
首先来看个demo,这个demo包含了你会用到的基本参数,通过它你也能对tweening有个大概认识。
tweening是什么?
从维基百科来看,tweening就是inbetweening的缩写。我不知道为什么觉得很好笑也许inbetweening不是一个好的起始词。现在我们回到正题,什么是tween?就是指从源点到目标点之间的插值。tween会简单地生成位于区间内的值,问题是那些值放在哪里。这是通过简单的函数来完成的,你可以在这里看到这些函数。
首先引入库文件
下载地址:https://github.com/sole/tween.js
<script type='text/javascript' src='tween.js'></script>
接下来制造一个Tween
我们的例子同demo一样,完成在坐标轴上来回移动一个球体的效果,x坐标轴从0到400,y坐标轴从300到50.
首先我们定义原始的position和target值。position变量的值会被tween.js不断更新直到等于target值。我们创建一个tween对象来帮助我们完成这件事。
var position = { x : 0, y: 300 };
var target = { x : 400, y: 50 };
var tween = new TWEEN.Tween(position).to(target, 2000);
注意到最后的2000了么?它表示tween会持续2s。为了使得3D对象动起来,我们需要告知它每一次的修改。这个通过onUpdate()函数完成。你如果想在tween结束后告知,可以使用onComplete()函数。
tween.onUpdate(function(){
mesh.position.x = position.x;
mesh.position.y = position.y;
});
想要调整它么?
让我们做更多的自定义吧~!延迟tween开始的时间500ms怎么样?
tween.delay(500)
很明显你也可以改变ease函数,从 这里选一个吧~!
tween.easing(TWEEN.Easing.Elastic.InOut)
开始运行
现在我们需要告诉库参数已经配置好了,可以开始运行了。
tween.start();
然后我们需要定期更新我们的tweens,这行代码同渲染循环结合的很好。
TWEEN.update();
完成啦~现在你可以疯狂地把tweening用在任何地方了!像我们这里用到的位置,以及颜色,大小,任何地方都可以~!
为动画链接Tweens
我们demo中的球不停地来回移动,是怎么做到的?我么需要链接tweens。它们将会依次执行。chain()提供了简单的方式来制造长效多样的动画。
/ after tweenHead, do tweenBack
tweenHead.chain(tweenBack);
// And after tweenBack, do tweenHead, so it is cycling
tweenBack.chain(tweenHead);
所以tween.js是一个小型库提供了简单的动画方式。你能够在 这里看到demo的源码。
Have fun~!