threejs texture loading (2)

We use the loader provided by threejs to load some maps as textures for geometry, which is very convenient. We use a local picture as an example to achieve this effect:

<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(3, 3, 3, 3, 3, 3);

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load("src/assets/css.jpg");

const Material = new THREE.MeshBasicMaterial({ map: texture });
const cube = new THREE.Mesh(Gemertry, Material);
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);
  // control.update();
};
render();
</script>
<style scoped>
</style>

 

The core code is here:

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load("src/assets/css.jpg");

const Material = new THREE.MeshBasicMaterial({ map: texture });
const cube = new THREE.Mesh(Gemertry, Material);
scene.add(cube);

We add the map attribute to the material and use texture as its value to implement the texture. What needs special attention here is that when textureLoader.load introduces the image path, it must be an absolute path.

Of course, we can also use imageLoader to load this image. The code is slightly different:

//图片加载器
 const textureLoader = new THREE.ImageLoader();
 textureLoader.load("src/assets/css.jpg", img => {
   let texture = new THREE.Texture(img);
   texture.needsUpdate = true;
   const Material = new THREE.MeshBasicMaterial({ map: texture });
   const cube = new THREE.Mesh(Gemertry, Material);
   scene.add(cube);
 });

For imageloader, we need to add texture.needsUpdate = true; this line of code to its callback to ensure normal loading.

Guess you like

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