在 Three.js 中设置颜色有多种方式,具体取决于你要为哪个部分设置颜色(如几何体颜色、材质颜色、顶点颜色等)。以下是常见的几种设置颜色的方法:
- 设置材质颜色
使用 MeshStandardMaterial 或 MeshBasicMaterial 等材质时,可以通过构造函数或 .color 属性来设置颜色。
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 }); // 绿色
// 或者
material.color.set(0xff0000); // 设置为红色
- 使用 THREE.Color 对象
const color = new THREE.Color(0x0000ff); // 蓝色
material.color = color;
- 为每个顶点设置颜色
如果你希望每个顶点有不同的颜色,可以使用顶点颜色属性。
步骤:
- 在几何体中添加 colors 属性数组。
- 使用 MeshStandardMaterial 并将 vertexColors 设为 true。
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 为每个顶点设置颜色
// 在 Three.js 和 WebGL(GPU)中,颜色值使用的是 [0, 1] 的浮点数范围。
geometry.setAttribute(
'color',
new THREE.BufferAttribute(new Float32Array([
1, 0, 0, // 红色
0, 1, 0, // 绿色
0, 0, 1, // 蓝色
1, 1, 0, // 黄色
1, 0, 1, // 品红
0, 1, 1 // 青色
]), 3)
);
const material = new THREE.MeshStandardMaterial({ vertexColors: true });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
- 设置环境光和光源颜色
你也可以通过光源来影响物体的颜色。
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // 白色环境光
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xff0000, 1); // 红色点光源
pointLight.position.set(2, 2, 2);
scene.add(pointLight);
- 修改整个场景背景颜色
你可以通过设置 scene.background 来改变背景颜色。
scene.background = new THREE.Color(0x202020); // 深灰色背景
// 或者设置渲染器的背景颜色
renderer.setClearColor(0xffffff,1.0); //1.0 不透明