Three.js中自定义UV坐标贴图举例超详细讲解_javascript技巧
1、当原始几何体没有 UV 信息
2、当默认 UV 无法满足纹理显示需求
4、材质设置使用了 map(纹理贴图)
纹理可能根本看不到。
或者整个纹理只出现在几何体的一个小角落(默认 UV 不匹配)。
甚至多个面公用同一张纹理,但位置都不对。
在 3D 渲染中,为了将 2D 图片(纹理)映射到 3D 几何体上,需要用到 UV 坐标:
const group = topPolygonMesh.object3d; if (!group) return; group.traverse(child => { if (child.isMesh && child.geometry && child.geometry.attributes.position) { const posAttr = child.geometry.attributes.position; const positions = posAttr.array; // 1. 计算 XY 投影平面的包围盒 let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (let i = 0; i < positions.length; i += 3) { const x = positions[i]; const y = positions[i + 1]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; }; const width = maxX - minX; const height = maxY - minY; // 2. 根据 bbox 生成新的 UV(按 XY 贴图) const uv = []; for (let i = 0; i < positions.length; i += 3) { const x = positions[i]; const y = positions[i + 1]; const u = (x - minX) / width; const v = (y - minY) / height; uv.push(u, v); }; // 3. 设置新的 UV child.geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2)); child.geometry.attributes.uv.needsUpdate = true; } })
使用你上面的逻辑:
const group = topPolygonMesh.object3d;if (!group) return;group.traverse(child => { if (child.isMesh && child.geometry && child.geometry.attributes.position) {
🔹 找到场景中的所有 Mesh,确保其包含几何体和位置(顶点)数据。
const posAttr = child.geometry.attributes.position;const positions = posAttr.array;let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;for (let i = 0; i < positions.length; i += 3) { const x = positions[i]; const y = positions[i + 1]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y;}const width = maxX - minX;const height = maxY - minY;
📌 获取几何体在 XY 平面上的包围盒
const uv = [];for (let i = 0; i < positions.length; i += 3) { const x = positions[i]; const y = positions[i + 1]; const u = (x - minX) / width; const v = (y - minY) / height; uv.push(u, v);}
📌 将 XY 坐标归一化为 UV 区间
child.geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));child.geometry.attributes.uv.needsUpdate = true;
该段代码的最终目标是:✅ 使 XY 平面上的任意不规则几何体,都能准确、完整地显示一张贴图(通常是一张地图或图案)
到此这篇关于Three.js中自定义UV坐标贴图的文章就介绍到这了,更多相关Three.js自定义UV坐标贴图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
本文地址: https://www.earthnavs.com/jishuwz/a64b878be1203db6455a.html



















