Particle Animation(成功)

ThreeJS
canvas { display: block; }

Three.jsの読み込み

<script src="https://unpkg.com/three@0.142.0/build/three.min.js"></script>

シーンの定義

const scene = new THREE.Scene();

カメラの定義

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set = (0, 0, 5);

引数は画角、アスペクト比、描画開始距離、描画終了距離 の4つが必要です

その後、カメラの初期座標を設定しています

レンダラーの定義

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innderWidth, window.innderHeight);
document.body.appendChild(renderer.domElement);

レンダラーとはキャンバスに描画する物体のことです

パーティクルの生成

const particleCount = 1000;
const positions = new Float32Array(particleCount * 3);

1000粒の粒子を3D空間(x,y,z)に配置します(なので*3)

パーティクルの座標をランダムに設定してGeometryに適用

for (let i = 0; i < particleCount * 3; i++) {
    positions[i] = (Math.random() - 0.5) * 10;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));

-5 ~ +5 の範囲でランダムに配置します

position属性にランダム座標を適用させます

Materialを設定

const material = new THREE.PointsMaterial({ color: 0xffffff, size: 0.05 });

マテリアル … 形状はPointsMaterial(点)、色が0xffffff、サイズが0.05

GeometryとMaterialをもとに描画します

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

アニメーション

function animate() {
    requestAnimationFrame(animate);
    particles.rotation.y += 0.001;
    particles.rotation.x += 0.0005;
    renderer.render(scene, camera);
}
animate();

requestAnimationFrame()により毎フレーム自動でループ??

particles全体をrotation(回転)させます

ウィンドウのリサイズに対応

window.addEventListener('resize', () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
});

ウィンドウサイズが変わっても、画面が崩れないようにするためのおまじない

BACK