Three.jsで線を描画する方法を試してみます。
サンプルコード
線のジオメトリにはBufferGeometryのsetFromPointsを、マテリアルにはLineBasicMaterialかLineDashedMaterialを使用します。
import * as THREE from 'three'; import {OrbitControls} from 'three/addons/controls/OrbitControls.js'; // シーンの作成 const scene = new THREE.Scene(); // カメラの作成 const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // ヘルパーの表示 const axesHelper = new THREE.AxesHelper(1000); scene.add(axesHelper); // レンダラーの作成 const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // カメラ操作の設定 const controls = new OrbitControls(camera, renderer.domElement); // カメラの位置変更と更新 camera.position.set(100, 100, 100); controls.update(); // ラインの作成 const points = []; points.push(new THREE.Vector3(-50, 0, 0)); points.push(new THREE.Vector3(0, 50, 0)); points.push(new THREE.Vector3(50, 0, 0)); const geometry = new THREE.BufferGeometry().setFromPoints(points); const material = new THREE.LineBasicMaterial({ color: "orange" }); const line = new THREE.Line(geometry, material); scene.add(line); renderer.render(scene, camera); function animate() { renderer.render(scene, camera); } renderer.setAnimationLoop(animate);
線の座標はpointsの配列で作成していて、上記の場合はX軸(赤色)の方向に-50→0→50と進む間に、Y軸(黄緑色)の方向に0→50→0と進むオレンジの線が描画できました。
線を引くデモページ
上記を少し発展させて、ランダムに多数の線を描画する処理を作成してみます。
import * as THREE from 'three'; import {OrbitControls} from 'three/addons/controls/OrbitControls.js'; // シーンの作成 const scene = new THREE.Scene(); // カメラの作成 const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // ヘルパーの表示 const axesHelper = new THREE.AxesHelper(1000); scene.add(axesHelper); // レンダラーの作成 const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // カメラ操作の設定 const controls = new OrbitControls(camera, renderer.domElement); // カメラの位置変更と更新 camera.position.set(100, 100, 100); controls.update(); // ラインの作成 const lineLength = 100; const material = new THREE.LineBasicMaterial({ color: "gray" }); for (let i = 0; i < lineLength; i++) { const points = []; points.push(new THREE.Vector3( getRandomInt(-300, 300), getRandomInt(-300, 300), getRandomInt(-300, 300) )); points.push(new THREE.Vector3( getRandomInt(-300, 300), getRandomInt(-300, 300), getRandomInt(-300, 300) )); const geometry = new THREE.BufferGeometry().setFromPoints(points); const line = new THREE.Line(geometry, material); scene.add(line); } renderer.render(scene, camera); function getRandomInt(min, max) { return Math.floor( Math.random() * (max - min + 1) ) + min; } function animate() { renderer.render(scene, camera); } renderer.setAnimationLoop(animate);
コメントが承認されるまで時間がかかります。