<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta name = "viewport" content = "width=device-width, initial-scale = 1.0">
<title>テスト</title>
<style>
#canvas {
    display: block;
    margin-bottom: 10px;
}
</style>
</head>

<body>
<canvas id="canvas"></canvas>

<script type="module">
    import * as THREE from "https://cdn.jsdelivr.net/npm/three@0.167.0/build/three.module.js";

    // サイズを指定
    const width = 360;
    const height = 360;

    // レンダラー,シーン,カメラを作成
    const renderer = new THREE.WebGLRenderer({
        canvas: document.getElementById('canvas'),
    });
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(45, width / height);

    window.onload = () => {
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(width, height);
        camera.position.set(0, 0, 150);

        addObjects();

        const INTERVAL = 1000 / 60;
        let nextUpdateTime = new Date().getTime() + INTERVAL;
        frameProc();

        function frameProc(){
            const curTime = new Date().getTime();
            if(nextUpdateTime < curTime){
                nextUpdateTime +=  INTERVAL;
                update();
            }
            requestAnimationFrame(() => frameProc());
        }
    }

    let sprites = [];

    function addObjects(){
        for(let i=0; i<100; i++){
            /** @type {THREE.Sprite} */
            const sprite = createSprite();
            sprite.position.x = Math.random() * 200 - 100; // -100 ~ +100
            sprite.position.y = Math.random() * 200 - 100; // -100 ~ +100
            sprite.position.z = Math.random() * 1000 - 900; // 100 ~ -900
            sprites.push(sprite);
            scene.add(sprite);
        }
    }

    function createSprite(){
        const texture = new THREE.TextureLoader().load('./images/star.png');
        texture.colorSpace = THREE.SRGBColorSpace;
        const material = new THREE.SpriteMaterial({ map: texture, });
        const sprite = new THREE.Sprite(material);
        sprite.scale.set(20, 20, 20); // サイズ調整
        return sprite;
    }

    // 更新処理
    function update() {
        for(let i=0; i<sprites.length; i++){
            const sprite = sprites[i];
            sprite.position.z += 4;
            if(sprite.position.z > 150)
                sprite.position.z = -1000;
        }
        renderer.render(scene, camera); // レンダリング
    }
</script>
</body>
</html>