基于网格高度Three.js的颜色

时间:2018-05-19 14:06:47

标签: javascript colors three.js mesh

我正在使用Three.js中的STLLoader()加载STL文件,并将其转换为网格。现在,我想基于其高度为我的网格的每个立方体着色,如此处附加的图像screenshot-color-by-height。这可能在Three.js内,如果是这样,最好的方法是什么?实际模型如下:

https://casagroupproject.github.io/subpage1.html

1 个答案:

答案 0 :(得分:1)

关于如何使用顶点颜色制作它的概念:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(2, 5, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.setScalar(10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

var planeGeom = new THREE.PlaneBufferGeometry(10, 10, 10, 10);
planeGeom.rotateX(-Math.PI * 0.5);
var yMin = 0;
var yMax = 2;
var colors = [];
for (let i = 0; i < planeGeom.attributes.position.count; i++) {
  let yVal = THREE.Math.randInt(yMin, yMax);
  let yNorm = (yVal - yMin) / (yMax - yMin);
  planeGeom.attributes.position.setY(i, yVal);
  colors.push(yNorm, yNorm, 1);
}
planeGeom.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));
planeGeom.computeVertexNormals();

var mesh = new THREE.Mesh(planeGeom, new THREE.MeshStandardMaterial({
  vertexColors: THREE.VertexColors
}));
scene.add(mesh)

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>