【Three.js】オブジェクトを生成する

addメソッドでジオメトリとマテリアルから作成したメッシュをシーンに追加する。

window.addEventListener('load', init);

function init() {
  const width = 640;
  const height = 480;

  const renderer = new THREE.WebGLRenderer({
    canvas: document.querySelector('#myCanvas')
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(width, height);

  const scene = new THREE.Scene();

  const camera = new THREE.PerspectiveCamera(60, width / height);
  camera.position.set(15, 15, 15);
  camera.lookAt(new THREE.Vector3(0, 0, 0));

  const cube_geometry = new THREE.BoxGeometry(1, 1, 1);
  const cube_material = new THREE.MeshNormalMaterial();
  const cube = new THREE.Mesh(cube_geometry, cube_material);
  scene.add(cube);
  
  const plane_geometry = new THREE.PlaneGeometry(10, 10, 1, 1);
  const plane_material = new THREE.MeshBasicMaterial({color: 0xffffff});
  const plane = new THREE.Mesh(plane_geometry, plane_material);
  scene.add(plane); 
  
  const axes = new THREE.AxesHelper(12);
  scene.add(axes);

  renderer.render(scene, camera);
}

今回は、以下のように出力される。

add-mesh-to-scene by inoha_naito -p5.js Web Editor
A web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators,...

参考

three.js docs
three.js docs
three.js docs

タイトルとURLをコピーしました