2
1

More than 1 year has passed since last update.

Node.jsでThree.jsを使う方法

Posted at

いつも忘れるので...

ディレクトリ内にindex.html,script.js(とその他必要な)ファイルを用意

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Node.jsでThree.js</title>
        <link rel="stylesheet" href="style.css">
        <script type="module" src="script.js"></script>
    </head>
    <body>
        <h1>Hello, World</h1>
        <div id="webgl"></div>
    </body>
</html>
script.js
import * as THREE from 'three';

let scene, camera, renderer;

function init(){
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,1,1000);
    camera.position.set(0,15,0);
    camera.lookAt(0,0,0);

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0x000000);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);

    //環境光
    let ambientLight = new THREE.AmbientLight(0xcccccc,0.1);
    scene.add(ambientLight);

    //平行光源
    let directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    directionalLight.position.set(10, 100, 0);
    scene.add(directionalLight);

    //立方体を一つ描画
    let boxGeometry = new THREE.BoxGeometry(5,5,5);
    let boxMaterial = new THREE.MeshLambertMaterial({
        color:0xff0000
    });
    let box = new THREE.Mesh(boxGeometry, boxMaterial);
    box.position.set(0,0,0);
    box.rotation.x = Math.PI * 0.5
    scene.add(box);
    //console.log(box);
    
    document.getElementById('webgl').appendChild(renderer.domElement);

    render();

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

window.onload = init;

style.css
*{
    margin: 0;
    padding: 0;
    list-style: none;
}

ターミナルでthreeとviteをインストール

Three.js本体をインストール

npm install --save three

ビルドツール「Vite」をインストールして実行

npm install --save-dev vite
npx vite

npx viteを実行すると、ターミナルに Local: http://127.0.0.1:0000/ のように表示されるので、こちらにブラウザでアクセスすると、実行結果が表示されます。

止め方

Ctrl + C でサーバーが停止します。

参考

2
1
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
2
1