使用threejs从折线点创建平面

时间:2019-11-22 14:12:51

标签: javascript three.js 3d plane

我正在努力实现以下目标:

enter image description here

我有一个Polyline及其点,现在我想创建一个与图中所示相同的图纸。上方是折线,下方是从该折线点创建的图纸。

我遵循了这篇帖子Extruding a line in three.js的解决方案,但是当我尝试这样做时,它什么也没有呈现。

这是我尝试的代码:

let containerThreeJs = document.getElementById('threed-view-container');
let w = containerThreeJs.offsetWidth;
let h = containerThreeJs.offsetHeight;

let renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(w, h);
containerThreeJs.appendChild(renderer.domElement);

let scene = new THREE.Scene();

let camera = new THREE.PerspectiveCamera(5, 1, 1, 1000);
camera.position.setScalar(300);

let threeDpoints = [
  [88.5, 370],
  [229.5, 268],
  [300.5, 333],
  [373.5, 290],
  [426.5, 392]
];

let geometry = extrudePath(threeDpoints, 100);

var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  side: THREE.DoubleSide
});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

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

render();

function resize(renderer) {
  const canvas = renderer.domElement;
  const width = canvas.clientWidth;
  const height = canvas.clientHeight;
  const needResize = canvas.width !== width || canvas.height !== height;
  if (needResize) {
    renderer.setSize(width, height, false);
  }
  return needResize;
}

function render() {
  if (resize(renderer)) {
    camera.aspect = canvas.clientWidth / canvas.clientHeight;
    camera.updateProjectionMatrix();
  }
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

function extrudePath(points, depth) {
  var geometry = new THREE.PlaneGeometry(10, 10, points.length - 1, 1);
  var vertices = geometry.vertices;
  // if I comment this loop then the plane is visible
  for (var i = 0, l = points.length, p; i < l; i++) {
    p = points[i];

    vertices[i].x = vertices[i + l].x = p[0];
    vertices[i].y = vertices[i + l].y = p[1];

    vertices[i].z = p[2];
    vertices[i + l].z = p[2] + depth;
  }

  geometry.computeFaceNormals();

  return geometry;
}
<script src="http://mrdoob.github.io/three.js/build/three.min.js"></script>
<script src=http://mrdoob.github.io/three.js/examples/js/controls/OrbitControls.js></script>
<div id="threed-view-container" style="width: 100%; height: 500px"></div>

如果我从extrudePath中删除了for循环,那么简单的平面是可见的,但是如果我保留它,似乎什么都无法渲染。

1 个答案:

答案 0 :(得分:0)

我不确定,但是我看到了这一点:在点数组threeDpoints中,每个点都有2个部分。但是在extrudePath函数中,它正在寻找3。(p [0],p [1],p [2])

`let threeDpoints = [
    [88.5, 370],
    [229.5, 268],
    [300.5, 333],
    [373.5, 290],
    [426.5, 392]
];
`

`p = points[i];
vertices[i].x = vertices[i + l].x = p[0];
vertices[i].y = vertices[i + l].y = p[1];
vertices[i].z = p[2];
vertices[i + l].z = p[2] + depth;`