Three.js 顶点颜色教程

Three.js 顶点颜色教程 顶点颜色 ·Vertex Color· ▶ 在线运行案例案例合集三维可视化功能案例threehub.cn开源仓库github地址https://github.com/z2586300277/three-cesium-examples400个案例代码:网盘链接你将学到什么geometry.attributes.color为每个顶点指定 RGB材质vertexColors: true启用顶点插值着色GPU 如何在三角面内插值顶点颜色效果说明三角形的每个顶点颜色不同面片内部呈现平滑渐变GPU 对三个顶点颜色做重心坐标插值。核心概念顶点属性 pipelineattributes.position → 顶点位置attributes.color → 顶点颜色 (RGB, 0~1) attributes.normal → 法线光照计算 attributes.uv → 纹理坐标const colors new Float32Array([1, 1, 1, // 顶点0 白 1, 1, 0, // 顶点1 黄 1, 1, 1, // 顶点2 白 1, 0, 0, // 顶点3 红 0, 1, 1, // 顶点4 青 0, 0, 1, // 顶点5 蓝 ]); geometry.attributes.color new THREE.BufferAttribute(colors, 3);vertexColors材质必须开启vertexColors: true或传入THREE.VertexColors常量旧版 API否则只用material.colornew THREE.PointsMaterial({vertexColors: true, // 使用 attributes.color size: 10.0 });插值原理三角形内任意点的颜色 三个顶点颜色按距离加权平均。这是 GLSL varying 变量的基础机制自定义 shader 同样适用。实现步骤定义 position color 两组 BufferAttributePointsMaterial 开启 vertexColors分别用 Points 和 Mesh 展示本案例两者共用 material代码要点import * as THREE from three; import { OrbitControls } from three/examples/jsm/controls/OrbitControls.jsconst scene new THREE.Scene();// 网格模型Mesh其实就一个一个三角形(面)拼接构成 const geometry new THREE.BufferGeometry(); const vertices new Float32Array([ 0, 0, 0, 50, 0, 0, 50, 0, 50,0, 0, 0, 0, 0, 50, 50, 0, 50, ]);geometry.attributes.position new THREE.BufferAttribute(vertices, 3);const colors new Float32Array([ 1, 1, 1, //顶点1颜色 1, 1, 0, //顶点2颜色 1, 1, 1, //顶点3颜色 1, 0, 0, //顶点4颜色 0, 1, 1, //顶点5颜色 0, 0, 1, //顶点6颜色 ]); geometry.attributes.color new THREE.BufferAttribute(colors, 3)// 点颜色 const material new THREE.PointsMaterial({ vertexColors: colors, size: 10.0 }) const points new THREE.Points(geometry, material) scene.add(points)// 网格颜色 const mesh new THREE.Mesh(geometry, material) scene.add(mesh)// AxesHelper const axesHelper new THREE.AxesHelper(150); scene.add(axesHelper);// 相机 const camera new THREE.PerspectiveCamera(); //相机 camera.position.set(200, 200, 200); //相机位置 camera.lookAt(0, 0, 0); //相机观察位置// 渲染器 const renderer new THREE.WebGLRenderer(); // 创建渲染器 const box document.getElementById(box); renderer.setSize(box.clientWidth, box.clientHeight); //渲染区域 renderer.render(scene, camera); //执行渲染 box.appendChild(renderer.domElement);;const controls new OrbitControls(camera, renderer.domElement); controls.addEventListener(change, function () { renderer.render(scene, camera); });完整源码GitHub小结本文提供顶点颜色完整 Three.js 源码与在线 Demo建议先运行案例再改 uniform/参数做二次实验更多 Three.js 实战案例见 three-cesium-examples 合集 与 GitHub 开源仓库