javascript - 请问要如何让构件依时间转动(动画)?

查看:72
本文介绍了javascript - 请问要如何让构件依时间转动(动画)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

请问有办法让一个构件在画面上像动画一样一直转动吗?

Autodesk Forge 微信讨论群 – pochao 提问

解决方案

您好,你可以透过 requestAnimationFramesetTimeout 这两个函数搭配来达成,请看下方示例(ES2015代码):

class RotateExt extends Autodesk.Viewing.Extension {
  constructor( viewer, options ) {
    super( viewer, options );
  }

   load() {
    this.actived = true;
    this.viewer.addEventListener( Autodesk.Viewing.SELECTION_CHANGED_EVENT, this.onSelectionChanged );
    return true;
   }

   unload() {
    this.actived = false;
    this.viewer.removeEventListener( Autodesk.Viewing.SELECTION_CHANGED_EVENT, this.onSelectionChanged );
    return true;
   }
   
   onSelectionChanged = ( event ) => {
    this.model = event.model;
    this.fragIdsArray = event.fragIdsArray;

    // 要求第一个动画 frame
    requestAnimationFrame( this.rotateHandler );
  };

  /**!
   * 关键函数
   */
  rotateHandler = () => {
    if( !this.actived ) return;

    const quaternion = new THREE.Quaternion();
    // 设置旋转量 - 依 Y 轴旋转构件 60 度
    quaternion.setFromAxisAngle( new THREE.Vector3( 0,1,0 ), Math.PI / 3 );

    const model = this.model;
    const fragIdsArray = this.fragIdsArray;

    fragIdsArray.forEach( ( fragId, idx ) => {
      const fragProxy = this.viewer.impl.getFragmentProxy( model, fragId );

      fragProxy.getAnimTransform();

      const position = new THREE.Vector3( fragProxy.position.x, fragProxy.position.y, fragProxy.position.z );
      position.applyQuaternion( quaternion );

      fragProxy.position = position;
      fragProxy.quaternion.multiplyQuaternions( quaternion, fragProxy.quaternion );

      if( idx === 0 ) {
        const euler = new THREE.Euler();
        euler.setFromQuaternion( fragProxy.quaternion, 0 );
      }

      fragProxy.updateAnimTransform();
    });

    this.viewer.impl.sceneUpdated( true );
    
    // 500毫秒后要求下一个动画 frame
    setTimeout( () => {
        requestAnimationFrame( this.rotateHandler );
    }, 500 );
  };
}

Autodesk.Viewing.theExtensionManager.registerExtension( 'Autodesk.ADN.Viewing.Extension.RotateTool', RotateExt );

这篇关于javascript - 请问要如何让构件依时间转动(动画)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆