【Three.js】マテリアルのテスクチャーに画像や動画を設定する方法(デモ付き)

2023年11月16日WebGL & Three.js

Three.jsでマテリアルのテスクチャーに画像や動画を設定する方法を紹介します。
さっそくデモを確認してみましょう。

Three.jsのShaderMaterialを使ってGLSLを記述した画像の貼り方が知りたい場合は、【WebGL】Three.jsのShaderMaterialを使って画像や動画を出力する方法(デモ付き)を参考にしてみてください。

マテリアルのテスクチャーに画像や動画を設定するコード

async function initializeThreeJS() {
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );

  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  
  document.body.appendChild(renderer.domElement);
 
  const geometry = new THREE.PlaneGeometry(20, 10);

  // texture: 質感を意味するが、3Dでは画像や動画も含まれる
  // textureのloaderを読み込み
  const texLoader = new THREE.TextureLoader();
  // texLoaderが非同期処理なのでawait
  // textureを設定
  const texture = await texLoader.loadAsync(
    // "https://picsum.photos/800/400?random=1"
    "/img/img.jpg"
  );
  // mapを使ってtextureを設定
  const material = new THREE.MeshBasicMaterial({ map: texture });

  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  camera.position.z = 30;

  function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x = cube.rotation.x + 0.01;
    cube.rotation.y += 0.01;

    renderer.render(scene, camera);
  }

  animate();
}
initializeThreeJS();

上の一連の流れは以下の記事が参考になります。
もしThree.jsの基本的な操作の一連の流れを知らないという場合は、Three.jsの基本的な操作の一連の流れがとても短くまとめた記事なので参考にしてみてください。
具体的なコードとデモが見たい場合は、【WebGL&Three.js入門】Three.jsの一番シンプルなサンプルコードのチュートリアルの解説でデモもみれる状態にしているので参考にしてみてください。
今回はテクスチャーの設定がメインのためtextureの部分に焦点をあてて説明します。

3Dグラフィクスのテクスチャー

textureは質感を意味しますが、3Dでは画像や動画も含まれます。
つまり、textureに画像や動画を設定します。
具体的には以下の記述部分です。

  // textureのloaderを読み込み
  const texLoader = new THREE.TextureLoader();

ここで、textureのloaderをインスタンス化しています。
この処理は非同期処理なのでasync awaitを使います。

  // textureを設定
  const texture = await texLoader.loadAsync(
    // "https://picsum.photos/800/400?random=1"
    "/img/img.jpg"
  );

imgのパスは適宜変更しましょう。
動画の場合もパスさえあえば同様に可能です。
awaitをつけるので、忘れずにfunctionにasyncをつけます。

async function initializeThreeJS() {
...
}

そして、mapします。

  // mapを使ってtextureを設定
  const material = new THREE.MeshBasicMaterial({ map: texture });

このマテリアルは、textureを使いますよという意味になります。

テクスチャーを切り替える

  const material = new THREE.MeshBasicMaterial({ map: texture });

  const newTexture = await texLoader.loadAsync("/img/newImg.jpg");
  setTimeout(() => {
    material.map = newTexture;
  }, 3000);
  const cube = new THREE.Mesh(geometry, material);

テクスチャーを切り替えたい場合、上のように、別の画像などを新しい変数に格納して、
mapに格納することで切り替えることが可能です。