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

Three.js - 使用 Tween.js 实现动画效果

祁彬
2023-12-01

tween.js是一个小型的javaScript库,其github地址是https://github.com/tweenjs/tween.js 通过这个插件可以是用来定义,某个属性值之间的过渡,自动计算出起始值和结束值之间的所有中间值,这个过程叫做tweening补间。
示例:
https://ithanmang.gitee.io/threejs/home/201808/20180829/05-animation-tween.html
引入库文件:

<script src="../../libs/tween/Tween.js"></script>

例如:将一个网格x轴上的位置,在一秒内从10递减到3

let tween = new TWEEN.Tween({x:10}).to({x:3}, 1000);
tween.easing(TWEEN.Easing.Elastic.InOut);
tween.onUpdate(function () {
	// update the mesh
});

上面的例子中创建了一个TWEEn.Tween对象,这个对象可以保证x属性在1000毫秒之内,从10变化到3,通过Tween.js还可以在指定时间内属性变化方式,是线性的还是指数型。
属性值在指定时间内的变化称为easing缓动,在Tween.js中可以使用easing()函数来配置缓动效果。
示例中使用上一节的粒子系统的例子,实现的效果是,让所有的粒子来回向上和向下移动,通过下面这段代码可以实现

let position = {y: 1};

let tween = new TWEEN.Tween(position).to({y:0}, 5000);
tween.easing(TWEEN.Easing.Sinusoidal.InOut);

let tweenBcak = new TWEEN.Tween(position).to({y:1}, 5000);
tweenBcak.easing(TWEEN.Easing.Sinusoidal.InOut);

tween.chain(tweenBcak);
tweenBcak.chain(tween);

// 获取顶点个数
let count = geometry.getAttribute('position').count;

let onUpdate = function () {

   let y = this.y;

   let vertexs = [];

   for (let i = 0; i < count; i++ ) {

       vertexs.push(geometry.localPosition[i * 3] );
       vertexs.push(((geometry.localPosition[i * 3 + 1] +  3.22544) * y) -  3.22544);
       vertexs.push(geometry.localPosition[i * 3 + 2]);

   }

   geometry.getAttribute('position').array = new Float32Array(vertexs);
   geometry.getAttribute('position').needsUpdate = true;

};

tween.onUpdate(onUpdate);
tweenBcak.onUpdate(onUpdate);

tween.start();

上面这段代码中,创建了两个补间对象,tweentweenBack第一个是定义y属性从1过渡到0,第二个正好相反。
然后通过chain()函数,将这两个补间链接到一起。
示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>补间动画</title>
    <style>
        body {
            margin: 0;
            overflow: hidden; /* 溢出隐藏 */
        }

        #loading {
            position: fixed;
            top: 50%;
            left: 50%;
            color: #FFFFFF;
            font-size: 20px;
            margin-top: -30px;
            margin-left: -40px;
        }
    </style>
    <script src="../../libs/build/three-r93.js"></script>
    <script src="../../libs/examples/js/Detector.js"></script>
    <script src="../../libs/examples/js/libs/dat.gui.min.js"></script>
    <script src="../../libs/examples/js/libs/stats.min.js"></script>
    <script src="../../libs/examples/js/controls/OrbitControls.js"></script>
    <script src="../../libs/examples/js/loaders/PLYLoader.js"></script>
    <script src="../../libs/tween/Tween.js"></script>

</head>
<body>
<p id="loading">loading......</p>
<script>

    let scene, camera, renderer, controls, guiControls;
    let stats = initStats();

    /* 场景 */
    function initScene() {

        scene = new THREE.Scene();
        scene.background = new THREE.Color(0x050505);

    }

    /* 相机 */
    function initCamera() {

        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
        camera.position.set(-20, 0, 0);
        camera.lookAt(new THREE.Vector3(0, 0, 0));

    }

    /* 渲染器 */
    function initRender() {

        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setSize(window.innerWidth, window.innerHeight);

        document.body.appendChild(renderer.domElement);

    }

    /* 灯光 */
    function initLight() {

        scene.add(new THREE.AmbientLight(0x0c0c0c));

        let spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-100, -100, -100);

        let spotLight2 = new THREE.SpotLight(0xffffff);
        spotLight2.position.set(100, 100, 100);

        scene.add(spotLight);
        scene.add(spotLight2);

    }

    /* 控制器 */
    function initControls() {

        controls = new THREE.OrbitControls(camera, renderer.domElement);

        /* 属性参数默认 */

    }

    /* 调试插件 */
    function initGui() {

        guiControls = new function () {

        };

        let controls = new dat.GUI({width: 300});

    }

    /* 场景中的内容 */
    let loadGeometry;
    let points;

    function initContent() {

        let loader = new THREE.PLYLoader();
        loader.load('../../models/ply/test.ply', function (geometry) {
            geometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, 2, 0));

            let mateial = new THREE.PointsMaterial({
                color: 0xffffff,
                size: 0.05,
                opacity: 0.5,
                transparent: true,
                blending: THREE.AdditiveBlending,
                map: generateSprite()
            });

            points = new THREE.Points(geometry, mateial);

            scene.add(points);
            document.getElementById('loading').style.display = 'none';

            // 保存一份默认的顶点信息
            let position = geometry.getAttribute('position').array;
            geometry.localPosition = [];
            for (let i = 0; i < position.length; i++ ) {

                geometry.localPosition.push(position[i]);

            }


            initTween(geometry);

        });

    }

    // 补间动画
    function initTween(geometry) {

        let position = {y: 1};

        let tween = new TWEEN.Tween(position).to({y:0}, 5000);
        tween.easing(TWEEN.Easing.Sinusoidal.InOut);

        let tweenBcak = new TWEEN.Tween(position).to({y:1}, 5000);
        tweenBcak.easing(TWEEN.Easing.Sinusoidal.InOut);

        tween.chain(tweenBcak);
        tweenBcak.chain(tween);

        // 获取顶点个数
        let count = geometry.getAttribute('position').count;

        let onUpdate = function () {

            let y = this.y;

            let vertexs = [];

            for (let i = 0; i < count; i++ ) {

                vertexs.push(geometry.localPosition[i * 3] );
                vertexs.push(((geometry.localPosition[i * 3 + 1] +  3.22544) * y) -  3.22544);
                vertexs.push(geometry.localPosition[i * 3 + 2]);

            }

            geometry.getAttribute('position').array = new Float32Array(vertexs);
            geometry.getAttribute('position').needsUpdate = true;

        };

        tween.onUpdate(onUpdate);
        tweenBcak.onUpdate(onUpdate);

        tween.start();

    }

    // from THREE.js examples
    function generateSprite() {

        let canvas = document.createElement('canvas');
        canvas.width = 16;
        canvas.height = 16;

        let context = canvas.getContext('2d');
        let gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2);
        gradient.addColorStop(0, 'rgba(255,255,255,1)');
        gradient.addColorStop(0.2, 'rgba(0,255,255,1)');
        gradient.addColorStop(0.4, 'rgba(0,0,64,1)');
        gradient.addColorStop(1, 'rgba(0,0,0,1)');

        context.fillStyle = gradient;
        context.fillRect(0, 0, canvas.width, canvas.height);

        let texture = new THREE.Texture(canvas);
        texture.needsUpdate = true;
        return texture;

    }


    /* 性能插件 */
    function initStats() {

        let stats = new Stats();

        document.body.appendChild(stats.domElement);

        return stats;

    }

    /* 窗口变动触发 */
    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);

    }

    /* 数据更新 */
    function update() {
        TWEEN.update();
        stats.update();

    }

    /* 初始化 */
    function init() {

        initScene();
        initCamera();
        initRender();
        initLight();
        initControls();
        initContent();
        initGui();

        /* 监听事件 */
        window.addEventListener('resize', onWindowResize, false);

    }

    /* 循环渲染 */
    function animate() {

        requestAnimationFrame(animate);
        renderer.render(scene, camera);
        update();

    }

    /* 初始加载 */
    (function () {
        console.log("three init start...");

        init();
        animate();

        console.log("three init send...");
    })();

</script>
</body>
</html>

 类似资料: