通过threejs提供的加载器我们去加载一些贴图作为几何体的纹理,非常方便。我们以本地一张图片作为例子来实现这个效果:
<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>
核心的代码就在这里:
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);
我们给材质添加map属性,把texture作为其值就嫩实现贴图。这里特别要注意的是textureLoader.load引入图片路径的时候必须是绝对路径
当然,我们同样可以采用imageLoader来加载这个图片。代码稍微有点不同:
//图片加载器
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);
});
对于imageloader而言,我们需要在其回调里加入 texture.needsUpdate = true;这行代码以确保正常加载