Angular2 使用 threejs Orbitcontrols

Angular2 using threejs Orbitcontrols

我正在尝试在我的 angular (cli) 2 应用程序中使用 threejs 示例。

所以我已经安装了 threejs :

npm install three --save

然后添加了打字:

npm install @types/three --save-dev

最后我的组件看起来像这样:

import { Component, OnInit } from '@angular/core';
import * as THREE from 'three';

@Component({
    selector: 'app-testthreejs',
    templateUrl: './testthreejs.component.html',
    styleUrls: ['./testthreejs.component.css']
})
export class TestthreejsComponent implements OnInit {
//
}

有了这个我可以毫无问题地使用三个中的一些功能。

我想使用 node_modules/three/examples/js/ 中可用的一些示例,更准确地说是 OrbitControl。打字让我在 visual studio 代码中自动完成:

但是当我尝试使用它时,我遇到了以下错误:

TypeError: WEBPACK_IMPORTED_MODULE_1_three.OrbitControls is not a constructor

有什么方法可以通过导入来提供 OrbitControls(和其他示例)吗? 我应该在 html 中简单地包含 control.js 吗?

处理此问题的最佳方法是什么?

终于找到了解决方案:

1- 通过 npm 安装 OrbitControls:

npm install three-orbit-controls --save

2- 在组件中导入三个和 OrbitControls:

import * as THREE from 'three';
var OrbitControls = require('three-orbit-controls')(THREE)

然后我可以做

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

新方法

只需从示例模块导入 OrbitControls

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

旧答案

尝试使用替代包 https://www.npmjs.com/package/three-orbitcontrols-ts

1.安装包

npm install --save three-orbitcontrols-ts

2。在您的文件中使用

import * as THREE from 'three';
import { OrbitControls } from 'three-orbitcontrols-ts';

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

由于你们中很少有人遇到我同样的问题,所以我将此作为答案发布,以使其更加明显。

上述解决方案有效,但您可能会遇到以下错误:

'Cannot find name 'require'

如果是这种情况,请添加 Grunk 建议的行:

declare const require: (moduleId: string) => any;

声明前:

var OrbitControls = require('three-orbit-controls')(THREE)

查看使用 Angular + Three.js 的工作示例,包括 OrbitControls 和 ColladaLoader:https://github.com/makimenko/angular-three-examples

目前,Three.js 示例未包含在模块中,在 Angular 打字稿代码中使用它们可能有点棘手。特别是,如果您不想安装额外的第三方依赖项。 solution/workaround 之一可能是:

首先,包括依赖项:

three
@types/three

其次,导入组件:

import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";

然后在代码中使用它:

this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);

希望这可以帮助你开始

猴子补丁也可以解决这个问题:

// this should be added in the main file of the application
import * as THREE from 'three';
window['THREE'] = THREE;
import 'three/examples/js/controls/OrbitControls';

无需在.angular-cli.json文件[=11]中添加任何ThreeJS相关脚本=]