LoginSignup
4

More than 3 years have passed since last update.

星空が綺麗だったのでthree.jsを使って簡易宇宙を創造してみた

Last updated at Posted at 2019-12-16

突然ですが、宮崎市も次第に寒くなってきましたね...
冬の夜は寒くて寒くて、外に出るのが憂鬱です。

そんな冬ですが個人的に好きな点があります。

それは、星空がとてもきれいなことです。
空気が乾燥している分、夏よりか圧倒的なスケール!

田舎の実家に戻ったときにふと空を見上げるとと、ても綺麗だったので、宇宙(星空?)をブラウザ上に再現したいと思います。
*ぱっと作ったのでショボい宇宙になりましたが...

使用技術・サービス

  • three.js(WebGL)
  • webpack
  • Netlify

参考

完成ページ

実装

ファイル構成等は https://github.com/niiharamegumu/three-js-sample を御覧ください。

three.jsのインストール

npm install three --save

たったこれだけのコードで作成することができました。

index.js
import * as THREE from "three";

const generateRenderer = (width, height, selector) => {
    const renderer = new THREE.WebGLRenderer({
        canvas: document.querySelector(selector)
    });

    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(width, height);

    return renderer;
}

const init = () => {

    const
        width = window.innerWidth,
        height = window.innerHeight,
        renderer = generateRenderer(width, height, "#canvas"),
        scene = new THREE.Scene(),
        camera = new THREE.PerspectiveCamera(100, width / height, 10000, 100),
        geometry = new THREE.SphereGeometry(),
        SIZE = 2000,
        POINT_NUM = 4000;

    camera.updateProjectionMatrix();
    camera.position.set(1, 1, +1000);

    for (let i = 0; i < POINT_NUM; i++) {
        geometry.vertices.push(new THREE.Vector3(
            SIZE * (Math.random() - 0.5),
            SIZE * (Math.random() - 0.5),
            SIZE * (Math.random() - 0.5),
        ));
    }
    const material = new THREE.PointsMaterial({
        size: 3,
        color: 0xFFFFFF,
    });

    const mesh = new THREE.Points(geometry, material);
    scene.add(mesh);

    run();

    function run() {
        mesh.rotation.y += 0.0001;
        renderer.render(scene, camera);

        requestAnimationFrame(run);
    }
}

  window.addEventListener('load', init);

まとめ

もう少し、ドキュメントや使い方を知ることができれば、複雑な3Dを作成することができるので、
もっと触ってみたいと思いました!
自分の好きな風景や物を再現できたら最高です!

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