Using Threejs + OrbitContols in TypeScript

前端 未结 14 1257
清歌不尽
清歌不尽 2021-02-07 11:59

I\'m not able to get this example of using the aforementioned combo going in TypeScript.

I have and <

相关标签:
14条回答
  • 2021-02-07 12:26

    Feeling kind of silly since the solution (or workaround at least) turns out to be quite simple...

    Just declare the OrbitControls variable:

    declare var THREE.OrbitControls: any; // even "declare var THREE.OrbitControls;" will do the trick
    

    There are still some compilation errors but it works.

    0 讨论(0)
  • 2021-02-07 12:28

    After adding the three-orbitcontrols typings and three-orbit-controls npm package (why aren't these named the same?), I was still having issues getting it to work in Typescript. This ended up working for me in case it's helpful for anyone else who doesn't want to use the workaround:

    import * as three from 'three';
    three.OrbitControls = require('three-orbit-controls')(three);
    
    let camera = new three.PerspectiveCamera(75, aspectRatio, 1, 1000);
    let renderer = new three.WebGLRenderer();
    let controls = new three.OrbitControls(camera, renderer.domElement);
    

    As of today, it seems that the OrbitControls npm package is using an old style of exports that requires an old-style require statement that passes in the Three library.

    0 讨论(0)
  • 2021-02-07 12:30

    After few hours spend on this problem, I ended up creating a new package: three-orbitcontrols-ts

    import * as THREE from 'three';
    import { OrbitControls } from 'three-orbitcontrols-ts';
    
    const controls = new OrbitControls(camera, renderer.domElement);
    
    0 讨论(0)
  • While previous answers may work out to some degree, you should go with the ready made definition files from DefinitelyTyped. They also define OrbitControl's properties and methods.

    0 讨论(0)
  • 2021-02-07 12:37

    outside ts:

    var THREEa = THREE;
    

    inside ts:

    var controls = new THREEa.OrbitControls(pCamera, pContainer);
    
    0 讨论(0)
  • 2021-02-07 12:38

    I tried some of the suggested solutions and could not get it to work right so after some experimentation, I ended up with:

    import * as THREE from 'three';
    import OrbitControlsLibrary = require('three-orbit-controls');
    var OrbitControls = OrbitControlsLibrary(THREE);
    ...
    this.controls = new OrbitControls(this.camera);
    

    I am using webpack bundling and with this I did not have to add the script tag in the HTML template.

    0 讨论(0)
提交回复
热议问题