threejs texture loading three (video loading)

In addition to using pictures as textures for geometry mapping, threejs can also use videos as textures for mapping settings. There are many types of textures, and we can use different loaders to load them. For videos as textures, we need to use today's protagonist: VideoTexture. Let’s look at the effect first:

 Let’s look directly at the code:

<template>
    <div>
    </div>
</template>
<script  setup>
import { ref } from "vue";

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as Dat from "dat.gui";
const gui = new Dat.GUI();
const scene = new THREE.Scene();
const camara = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camara.position.set(0, 0, 10);

const Gemertry = new THREE.BoxGeometry(5, 5, 5);

//视频加载器
let video = document.createElement("video");
video.src = "/src/assets/819.mp4";
video.load();
video.crossOrigin = "anonymous";

document.addEventListener("click", () => {
  video
    .play()
    .then(() => {
      render();
    })
    .catch(err => {
      console.log("err:", err);
    });
});
// video.play();
let texture = new THREE.VideoTexture(video);
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const materials = [
  new THREE.MeshBasicMaterial({ color: "#f90" }),
  new THREE.MeshBasicMaterial({ map: texture }),
  new THREE.MeshBasicMaterial({ color: "#63a" }),
  new THREE.MeshBasicMaterial({ color: "#e2d" }),
  new THREE.MeshBasicMaterial({ color: "#c57" }),
  new THREE.MeshBasicMaterial({ color: "#f00" })
];

const cube = new THREE.Mesh(Gemertry, materials);
scene.add(cube);

// 将网格对象添加到场景中

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

const control = new OrbitControls(camara, renderer.domElement);

const render = () => {
  renderer.render(scene, camara);
  requestAnimationFrame(render);
  if (video.readyState === video.HAVE_ENOUGH_DATA) {
    texture.needsUpdate = true;
  }
};
render();
</script>
<style scoped>
</style>

Special attention should be paid here: for videos. Many browsers disable default playback, so here we implement it by adding a click event to the document object, and then in the callback of successful loading, we need to call our render() function again.

Guess you like

Origin blog.csdn.net/baidu_41601048/article/details/132473921