three.jsを試す

記事中に3Dモデルを表示したい

サイトに3Dモデルを表示する試み①

まずはthree.jsのお試しから。

とりあえず立方体

<canvas id="myCanvas" style="width:100%;"></canvas>
<script src="/js/build/three.min.js"></script>
<script>
function main() {
    // Three.js Fundamentalsより
    // (https://threejsfundamentals.org/threejs/lessons/threejs-fundamentals.html)

    // 最初に必要なのは<canvas>タグ
    // Three.jsは<canvas>の中に描画するのでIDをつけて作成しておく
    const canvas = document.querySelector('#myCanvas');

    // canvasを設定したらWebGLRendererを作成
    // レンダラーとは与えられたデータを扱いcanvas内にレンダリングするもの
    const renderer = new THREE.WebGLRenderer({canvas, antialias: true});


    // カメラを設置
    const fov = 75;     // Field of View
    const aspect = 2;   // デフォルト
    const near = 0.1;
    const far = 5;
    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);

    // Z軸方向に少しずらす
    camera.position.z = 2;

    // シーンを作成
    const scene = new THREE.Scene();
    // シーンの背景色を灰色に変更(デフォルトは黒)
    scene.background = new THREE.Color( 0xaaaaaa );

    // テスト用モデルとして立方体のデータを含むBoxGeometryを作成
    // Three.jsで表示するほとんどのものは、3Dオブジェクトを形作る頂点を定義するジオメトリが必要
    const boxWidth = 1;
    const boxHeight = 1;
    const boxDepth = 1;
    const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

    // 光源がなくても発色するマテリアルMeshNormalMaterialを作成
    const material = new THREE.MeshNormalMaterial();

    // メッシュを作成
    // メッシュとはジオメトリ(オブジェクトの形状)とマテリアル(オブジェクトの材質)を組み合わせたもの
    const cube = new THREE.Mesh(geometry, material);

    // メッシュをシーンに追加
    scene.add(cube);

    // シーンをレンダリング
    renderer.render(scene, camera);

    // 立方体を正面から見ただけでは立体かどうか判りにくいので回転のアニメを加える
    function render(time) {
        time *= 0.0002;  // convert time to seconds

        cube.rotation.x = time;
        cube.rotation.y = time;

        renderer.render(scene, camera);

        requestAnimationFrame(render);
    }
    requestAnimationFrame(render);
}
main();
</script>

次はマウスコントロールを導入してみます。

3D 

関連記事