LoginSignup
6
6

More than 5 years have passed since last update.

three.jsのOrbitControlsをTypescriptで使う方法

Posted at

詰まったのでメモ。

webpack + three.jsで開発していたので、htmlに <script src="js/controls/OrbitControls.js"></script> とは書きたくなかったので、なんとかしてnpmパッケージで解決した。

three-orbitcontrols-tsをインストールする。

$ yarn add three-orbitcontrols-ts

three-orbitcontrols をインストールすると、@types/three-orbitcontrols が存在しないので型チェックができないため、最初から three-orbitcontrols-ts を入れてしまうのが良さそう。

tsファイルでインポートして使用する。

index.ts
import * as THREE from "three";
import { OrbitControls } from "three-orbitcontrols-ts";

const init = () => {
  const width = window.innerWidth;
  const height = window.innerHeight;

  // レンダラーを作成
  const renderer = new THREE.WebGLRenderer({
    canvas: document.getElementById("myCanvas") as HTMLCanvasElement
  });
  renderer.setSize(width, height);

  // カメラを作成
  const camera = new THREE.PerspectiveCamera(50, width / height);
  camera.position.set(0, 0, 1000);
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.update();
  ...
};

window.addEventListener("DOMContentLoaded", init);

three-orbitcontrols-ts が2年近くメンテナンスされていないのが心配だけれど、 @types/three-orbitcontrols が出るまではしばらく使っていきたい。

6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6