首页 > 解决方案 > three.js 中线条的颜色

问题描述

我有这样的代码:

  const materialLinearInterpolation = new THREE.LineBasicMaterial({ color: 0x0000c9, linewidth: 1 })
  const pointsLinearInterpolation = []
  for (var i = 0; i < this.pointsCoordinatesLinearInterpolation.length; i++) {
    pointsLinearInterpolation.push(
      new THREE.Vector3(
        this.pointsCoordinatesLinearInterpolation[i].x,
        this.pointsCoordinatesLinearInterpolation[i].y,
        this.pointsCoordinatesLinearInterpolation[i].z
      )
    )
  }
  const geometryLinearInterpolation = new THREE.BufferGeometry().setFromPoints(pointsLinearInterpolation)
  this.lineLinearInterpolation = new THREE.Line(geometryLinearInterpolation, materialLinearInterpolation)

  this.scene.add(this.lineLinearInterpolation)

我需要为线条使用多种颜色,这样的配置可以吗?如果不可能,我怎样才能绘制几条不同颜色的连接线

标签: javascriptthree.js

解决方案


如果您希望每条线段有不同的颜色,则必须使用THREE.LineSegment和顶点颜色,如下面的示例中所示:

let camera, scene, renderer;

init();
render();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 3;

  scene = new THREE.Scene();

  const geometry = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), new THREE.Vector3(-1, 0, 0)]);

  const colors = [
    255, 255, 0, 255, 255, 0,
    0, 255, 255, 0, 255, 255
  ];

  geometry.setAttribute('color', new THREE.Uint8BufferAttribute(colors, 3, true));

  const material = new THREE.LineBasicMaterial({
    vertexColors: true
  });

  const lines = new THREE.LineSegments(geometry, material);
  scene.add(lines);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function render() {

  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.130.1/build/three.min.js"></script>

相反,使用THREE.Line会在线条部分之间产生通常不需要的颜色渐变。


推荐阅读