LoginSignup
4
3

More than 3 years have passed since last update.

three.jsをwebpackで使う最小の環境構築

Posted at

three.jsをwebpackで使用するための最小限の構成です。
なお、実装時のライブラリとバージョンは以下のとおりです。

ライブラリ バージョン
three 0.120.1
webpack 4.44.1
webpack-cli 3.3.12
webpack-dev-server 3.11.0

パッケージのインストール

package.json を作成。


npm init -y

threewebpackwebpack-cliwebpack-dev-server をインストールします。

npm install webpack webpack-cli webpack-dev-server --save-dev
npm install three --save

package.json のscriptsに下記を追加します。

"scripts": {
    "start": "webpack-dev-server"
  },

webpack.config.jsの作成

webpack.config.js を作成します。

const webpack = require('webpack');

module.exports = [
    {
        // メインとなるJavaScriptファイル(エントリーポイント)
        entry: `./src/index.js`,

        output: {
            //  出力ファイルのディレクトリ名
            path: `${__dirname}/dist`,
            // 出力ファイル名
            filename: 'index.js'
        },
        // モード値を production に設定すると最適化された状態で、
        // development に設定するとソースマップ有効でJSファイルが出力される
        mode: "development",
        devServer: {
            contentBase: "dist",
            open: true
        },
        plugins: [
            // THREE.Scene などの形式で three.js のオブジェクトを使用できるようにする
            new webpack.ProvidePlugin({
                THREE : 'three/build/three'
            }),
        ]
    },
];

ファイルの作成

dist/index.html を作成。ブラウザでアクセスした時に表示されるhtmlになります。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>three.js demo</title>
    <script src="index.js"></script>
</head>
<body>
    <canvas id="myCanvas"></canvas>
</body>
</html>

src/index.jsの作成。
ここにコードを書きます。下記のコードはサンプルなので、実装したいものに合わせて適時編集してください。

window.addEventListener('load', init);

function init() {
  const width = 960;
  const height = 540;

  const renderer = new THREE.WebGLRenderer({
    canvas: document.querySelector('#myCanvas')
  });
  renderer.setSize(width, height);

  const scene = new THREE.Scene();

  const camera = new THREE.PerspectiveCamera(
    45,
    width / height,
    1,
    10000
  );
  camera.position.set(0, 0, 1000);

  const geometry = new THREE.BoxGeometry(500, 500, 500);
  const material = new THREE.MeshStandardMaterial({color: 0xff0000});
  const box = new THREE.Mesh(geometry, material);
  scene.add(box);

  const directionalLight = new THREE.DirectionalLight(0xffffff);
  directionalLight.position.set(1, 1, 1);
  scene.add(directionalLight);

  tick();

  function tick() {
    requestAnimationFrame(tick);
    box.rotation.x += 0.01;
    box.rotation.y += 0.01;
    renderer.render(scene, camera);
  }
}

実行

npm run start

を叩いて http://localhost:8080/にアクセスすると実行結果が確認できます。

スクリーンショット 2020-09-12 13.16.38.png

4
3
0

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
4
3