threejs教程-纹理贴图与环境贴图

206 阅读2分钟

简介

本系列教程需要具备threejs的基础入门知识,了场景、几何体、相机等基础概念。

学习本教程之前,建议学习笔者【基础网络材质】的基础知识

根据threejs前置知识,我们对如下的基础网络材质的一些属性已经有所了解物

现在,我们试着给图中的蓝色物体进行纹理贴图环境贴图

纹理贴图map

map属性是一个Texture纹理对象,这意味着想要给材质进行贴图,就必须使用TextureLoader先创建一个纹理贴图。TextureLoader我们并不陌生,它也可以给场景添加背景图片。

scene.background = new THREE.TextureLoader().load("/sky.png");

API地址:threejs.org/docs/?q=Tex…

TextureLoader是加载texture的一个类。 内部使用ImageLoader来加载文件。

TextureLoader语法回顾

语法结构:

new THREE.TextureLoader().load(url,onLoad,onProgress, onError);

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function )

  • url — 文件的URL或者路径,也可以为 Data URI.。vite项目中,public就是根目录。
  • onLoad — 加载完成时将调用。回调参数为将要加载的texture.
  • onProgress — 将在加载过程中进行调用。参数为XMLHttpRequest实例,实例包含total和loaded字节。
  • onError — 在加载错误时被调用。

纹理贴图代码示例

首先,我们准备一张照片放在vite的pubilc根目录。

// 创建纹理
const texture = new THREE.TextureLoader().load("/sky.png");
const material = new THREE.MeshBasicMaterial({
  // color: "blue",
  map: texture,
});

环境贴图envMap

环境贴图是环境对物体表面的影响,比如一个金属球表面可以看到周围的环境。

我们的场景已经有了6张图片的立方体背景:

// 1、创建3D场景对象Scene
const scene = new THREE.Scene();
// 添加背景颜色
const cubeTexture = new THREE.CubeTextureLoader()
  .setPath("/sky/")
  .load(["posx.jpg", "negx.jpg", "posy.jpg", "negy.jpg", "posz.jpg", "negz.jpg"]);
scene.background = cubeTexture;

现在,我们只要让我们的物体反射这个环境背景即可。为了好看一些,我们将立方体改成球体。

// 2、创建球体模型
const sphere = new THREE.SphereGeometry(20);

const material = new THREE.MeshBasicMaterial({
  envMap: cubeTexture,
});
const mesh = new THREE.Mesh(sphere, material);

效果展示:

完核心代码:

<template>
  <div class="wrap" ref="threeContainer"></div>
</template>

<script setup>
import * as THREE from "three";
import { onMounted, ref } from "vue";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

const threeContainer = ref(null);

// 1、创建3D场景对象Scene
const scene = new THREE.Scene();
// 添加背景颜色
const cubeTexture = new THREE.CubeTextureLoader().setPath("/sky/").load(["posx.jpg", "negx.jpg", "posy.jpg", "negy.jpg", "posz.jpg", "negz.jpg"]);
scene.background = cubeTexture;

// ....

// 2、创建球体模型
const sphere = new THREE.SphereGeometry(20);

const material = new THREE.MeshBasicMaterial({
  envMap: cubeTexture,
});
const mesh = new THREE.Mesh(sphere, material);
// 设置模型mesh的xyz坐标
mesh.position.set(0, 40, 0);
scene.add(mesh);

// 3、使用虚拟相机观察模型
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 50, 200);
camera.lookAt(0, 0, 20); //坐标原点

// 4、渲染3D场景到DOM上
const renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500); //设置three.js渲染区域的尺寸(像素px)
renderer.render(scene, camera);

onMounted(() => {
  threeContainer.value.appendChild(renderer.domElement);
});
</script>

<style scoped></style>