THREE.js 入门(六) 纹理、uv坐标

一、uv坐标

相当于x、y轴,通过自定义uv坐标可以截取所需的纹理范围

javascript 复制代码
<template>
  <div id="container"></div>
</template>

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

// 场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x666666);

// 相机
const camera = new THREE.PerspectiveCamera();
// camera.position.x = 10;
camera.position.y = 0;
camera.position.z = 2;

// 创建矩形
const geometry = new THREE.PlaneGeometry(1, 1)
const texture = new THREE.TextureLoader().load('/textureMsg/cloud.jpeg') // 纹理贴图

// UV像素的取值范围 分别为四个顶点的坐标 左上 右上 左下 右下
const uv = new Float32Array([
  0, 1,
  1, 1,
  0, 0,
  1, 0
])

// UV像素的颜色值
// const colors = new Float32Array([
//   1.0, 0.0, 0.0, // 红色
//   0.0, 1.0, 0.0, // 绿色
//   0.0, 0.0, 1.0  // 蓝色
// ]);

// const colorAttribute = new THREE.BufferAttribute(colors, 3); // 每个颜色有3个分量 (r, g, b)
// geometry.setAttribute('color', colorAttribute);


// // 设置矩形的uv 
geometry.attributes.uv = new THREE.BufferAttribute(uv, 2) // uv坐标 2表示只有x,y  3是x,y,z

// 材质
const material = new THREE.MeshBasicMaterial({
  side: THREE.DoubleSide, // 双面可见
  map: texture,  // 纹理贴图
  // vertexColors: true // 顶点颜色
})

console.log(geometry, 'geometry')

// 创建网格
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)

// 添加坐标辅助线
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );

onMounted(() => {
  // 渲染器
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 将渲染器添加到页面
  document.getElementById("container").appendChild(renderer.domElement);

  // 轨道控制器
  const controls = new OrbitControls(camera, renderer.domElement);

  // 动画
  function animate() {
    // 更新动画
    requestAnimationFrame(animate);

    // 轨道控制器更新
    controls.update();
    renderer.render(scene, camera);
  }
  animate();
});
</script>

二、效果

1、原图

2、截取后

相关推荐
应用市场1 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
Dfreedom.2 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生2 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
虚行2 小时前
C#上位机工程师技能清单文档
开发语言·c#
小羊在睡觉3 小时前
golang定时器
开发语言·后端·golang
CoderCodingNo3 小时前
【GESP】C++四级真题 luogu-B4068 [GESP202412 四级] Recamán
开发语言·c++·算法
saadiya~3 小时前
ECharts 实时数据平滑更新实践(含 WebSocket 模拟)
前端·javascript·echarts
百锦再3 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net
Larry_Yanan3 小时前
QML学习笔记(四十四)QML与C++交互:对QML对象设置objectName
开发语言·c++·笔记·qt·学习·ui·交互
百锦再4 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven