threejs基本知识5 (贴图)
TextureLoader / 贴图加载器
import Stats from "three/examples/jsm/libs/stats.module";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
let w = window.innerWidth; // 浏览器宽度
let h = window.innerHeight; // 浏览器高度
const scene = new THREE.Scene(); // 创建场景
const axes = new THREE.AxesHelper(10, 10, 10); // 坐标轴辅助器
// 方格辅助器
const grid = new THREE.GridHelper(10, 10, "red", "red");
const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 1000); // 创建相机 (视角 宽高比 最近距离 最远距离)
camera.position.set(0, 6, 3); // 相机位置
camera.lookAt(0, 0, 0); // 相机视角
// 基础环境光
const light = new THREE.AmbientLight("#ffffff", 0.2); // 创建灯光
// 创建贴图
const textureLoader = new THREE.TextureLoader();
const texture1 = textureLoader.load('/1.png');
const texture2 = textureLoader.load("/2.png");
const texture3 = textureLoader.load("/3.png");
const sphereGeometry = new THREE.SphereGeometry(0.4);
const sphere = new THREE.Mesh(
sphereGeometry,
new THREE.MeshBasicMaterial({ map: texture1 })
);
sphere.position.set(0, 1, 0);
sphere.castShadow = true;
const boxGeometry = new THREE.BoxGeometry(0.4, 0.4, 0.4);
// 立方体
const material1 = new THREE.MeshPhongMaterial({
// 在有贴图的情况下 打开颜色会叠加到贴图上
color: "red",
map: texture1,
});
const material2 = new THREE.MeshPhongMaterial({
map: texture2,
});
const material3 = new THREE.MeshPhongMaterial({
map: texture3,
});
// 立方体6个面都可以单独设置不同的贴图 Mesh 填充物体(物体创建后内存中的色值是0-1 => (1,0,0) 红色)
// 物体和灯光组合后呈现的色值为灯光色值和物体色值的乘积 (1,1,1)x(1,0,0) => (1,0,0) 红色
const cube = new THREE.Mesh(boxGeometry, [
material1,
material1,
material1,
material2,
material2,
material3,
]);
cube.position.set(0.8, 0.5, 0);
// Line 描边物体
const lineCube = new THREE.Line(boxGeometry, material1);
scene.add(sphere);
scene.add(cube);
scene.add(lineCube);
scene.add(light);
scene.add(dlHelper);
scene.add(axes);
scene.add(grid);
const renderer = new THREE.WebGLRenderer({}); // 创建渲染器
renderer.setSize(w, h); // 渲染器尺寸
renderer.shadowMap.enabled = true; // 场景开启阴影渲染
renderer.render(scene, camera); // 场景和相机放在渲染器中
const stats = new Stats(); // 刷新帧辅助器
document.getElementById("box-container").append(renderer.domElement);
document.getElementById("box-container").append(stats.domElement);
const orbitControls = new OrbitControls(camera, renderer.domElement); // 控制辅助器(鼠标滚动缩放、右击平移、左击旋转)
const clock = new THREE.Clock();
function render() {
const time = clock.getElapsedTime(); // 在不同频率下稳定增长的值
cube.rotation.z = time;
renderer.render(scene, camera); // 场景和相机放在渲染器中
stats.update();
orbitControls.update();
requestAnimationFrame(render);
}
render();
// 适配屏幕尺寸
window.addEventListener("resize", () => {
w = window.innerWidth;
h = window.innerHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
});