当前位置: 首页 > 工具软件 > Tween > 使用案例 >

利用Tween让动画更平滑(补间动画)

巢星纬
2023-12-01

我在  JavaScript 元素的滑动效果(一)JavaScript 元素的滑动效果(二)中用纯JS写的div动画滑动有卡顿,因为没有加入缓动函数,Tween封装了常用的缓动函数,所以正好利用一下。用Tween处理过的移动更加平滑(比德芙更丝滑)。

 

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.1.1/Tween.min.js"></script>
</head>

<body>
    <div></div>
</body>
<script type="text/javascript">
var box = document.createElement('div');
box.style.setProperty('background-color', '#008800');
box.style.setProperty('width', '100px');
box.style.setProperty('height', '100px');
document.body.appendChild(box);

function animate(time) {
    requestAnimationFrame(animate);
    TWEEN.update(time);
}
requestAnimationFrame(animate);

var coords = { x: 800, y: 800 };//假设有一个对象 position ,它的坐标为 x 和 y
var tween = new TWEEN.Tween(coords)
    .to({ x: 300, y: 200 }, 2000)//改变 x 的值从 100 到 200 ,持续时间为 1s
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(function() {//为了平滑的动画效果,需要在同一个循环动画中调用 TWEEN.update 方法
        box.style.setProperty('transform', 'translateX(' + coords.x + 'px');
    })
    .start();//创建 tween 对象后,激活它,从而让它开始动画
</script>

</html>

 类似资料: