Three.jsで配置する要素のサイズや色、位置などをランダムに配置する実装を試してみます。
サンプルコード
今回は複数の正十二面体の要素を、色とサイズと位置をランダムにして配置する例を実装してみます。
コードは下記の通りです。
import * as THREE from 'three';
// シーンの作成
const scene = new THREE.Scene();
// カメラの作成
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 10);
// レンダラーの作成
const renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor("white");
document.body.appendChild(renderer.domElement);
// ライトの作成
const directionalLight = new THREE.DirectionalLight("white", 3);
directionalLight.position.set(0, 0, 10);
scene.add(directionalLight);
// オブジェクトの作成
const objectCount = 150;
for (let i = 0; i < objectCount; i++) {
// ランダムなサイズ設定
const geometry = new THREE.DodecahedronGeometry(
Math.random() * 1 + 1 // 1~2
);
// ランダムな色設定
const color = new THREE.Color().setRGB(Math.random(), Math.random(), Math.random());
const material = new THREE.MeshStandardMaterial({
color
});
const object = new THREE.Mesh(geometry, material);
// ランダムな位置設定
object.position.set(
Math.random() * 40 - 20, // X: -20~20
Math.random() * 30 - 15, // Y: -15~15
Math.random() * 20 - 20 // Z: -20~0
);
scene.add(object);
}
renderer.render(scene, camera);
// リサイズの対応
const resize_canvas = () => {
const w = window.innerWidth;
const h = window.innerHeight;
renderer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.render(scene, camera);
}
window.addEventListener('resize', resize_canvas);
要素のサイズは26~29行目、位置は36~41行目で、Math.random()を使って特定の範囲内のランダムな値になるように設定しています。
色の設定は30~34行目で、setRGB()の引数が0.0~1.0の間の値を指定する形になっているので、Math.random()の値をそのまま使用しています。
色とサイズと位置がランダムな要素を複数配置するデモページ
コメントが承認されるまで時間がかかります。