JavaScriptの3D表示に興味がありまして、まずは簡単にThree.js入門サイトに例題がありました回転する地球を表示してみました。
ついでに回転する立方体を表示したところ、少々不気味な雰囲気になってしまいました(^^;。
The earth is always spinning.
下記ソースはローカルマシンで、VScodeのLive Serverでデバッグしてたものですので、サーバーでの公開の際は、サーバー環境に合わせて一部変更する必要あります。
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <!-- load test_th.js -->
        <script type="module" src="test_th.js"></script>
    </head>
    <body>
        <h1>The earth is always spinning.</h1>
        <canvas id="myCanvas"></canvas>
    </body>
</html>    
上記HTMLの<script>タグでは、type=”module”になっていることが注意です。
下記のJavaScriptファイル”test_th.js”では、ファイル1行目でThree.jsをimportしており、type=”module”属性にしなければimportできないためです。
上記HTML 10行目の<canvas>タグで設定したid=”myCanvas”に対して、下記JavaScriptで3D画像を生成し表示します。
import * as THREE from "./three.module.js";
function main() {
    const width = 960;
    const height = 540;
    // make Renderer
    const renderer = new THREE.WebGLRenderer({
        canvas: document.querySelector("#myCanvas")
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(width, height);
    // make Scene
    const scene = new THREE.Scene();
    // make Camera
    const camera = new THREE.PerspectiveCamera(
        45,
        width / height,
        1,
        10000
    );
    camera.position.set(0, 0, +1000);
    // make BOX
    const geometry = new THREE.BoxGeometry(200, 200, 200);
    const material = new THREE.MeshStandardMaterial({
        color: 0x0000ff
    });
    const box = new THREE.Mesh(geometry, material);
    scene.add(box);
    // make BALL
    const geometry2 = new THREE.SphereGeometry(200, 30, 30);
    // Read texture
    const loader = new THREE.TextureLoader();
    const texture = loader.load("imgs/earthmap1k.jpg");
    const material3 = new THREE.MeshStandardMaterial({
            map: texture
    });
    const ball = new THREE.Mesh(geometry2, material3);
    scene.add(ball);
    // Derection of Light
    const directionalLight = new THREE.DirectionalLight(
        0xffffff
    );
    directionalLight.position.set(1, 1, 1);
    // add to Scene
    scene.add(directionalLight);
    // Ambient of Light  (Parameter: color, strength of light)
    const ambientLight = new THREE.AmbientLight(0x008888, 0.8);
    scene.add(ambientLight);
    tick();
    function tick() {
        requestAnimationFrame(tick);
        // Rotate Box
        box.rotation.x += 0.01;
        box.rotation.y += 0.01;
        // move
        box.position.x += 0.1;
        box.position.y -= 0.01;
    
        // Rotate Ball
        ball.rotation.y += 0.01;
        // move
        ball.position.x -= 0.1;
        // renderering
        renderer.render(scene, camera);
    }
}
main();
このJavaScriptは球体と立方体を生成し、それぞれを回転させて表示しています。球体にはフリーの地球表面画像をテクスチャとして貼り付けて、地球っぽくしています。
また、カメラ位置や照明位置の設定もしています。
Three.jsを利用すると、3D表示がお手軽にできそうです。
上記ソースをこのサイト(WordPressで作成している)で表示できるように修正しています。ちゃんと地球が回って見えますでしょうか?
  
  
  
  

コメント