使用THREE.js的任何形状的可扩展轮廓

时间:2018-11-01 09:55:24

标签: javascript three.js

我应该首先说我是WebGL和THREE库的新手。我正在努力实现:

  • 向场景添加2D形状(正方形,三角形,圆形等)
  • 形状可以具有任意大小和位置
  • 形状应无填充,且轮廓应根据形状大小缩放

我尝试使用线框:

const geometry = new THREE.BoxGeometry(40, 40, 0);

const material = new THREE.MeshBasicMaterial({
  color: 0xff0000,
  wireframe: true,
});

const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

上面提供了以下内容:

  • 没有深度的3D盒子
  • 设置宽度为1的不可缩放轮廓
  • 穿过盒子的十字架

我也尝试了相同的方法,但是绘制了2D形状的点:

const shapeSize = 100;
const x = -shapeSize / 2;
const y = -shapeSize / 2;

const square = new THREE.Shape();

square.moveTo(x, y);
square.lineTo(x + shapeSize, y);
square.lineTo(x + shapeSize, y + shapeSize);
square.lineTo(x, y + shapeSize);
square.lineTo(x, y);

const geometry = new THREE.ShapeGeometry(square);

const material = new THREE.MeshBasicMaterial({
  color: 0xff0000,
  wireframe: true,
});

const mesh = new THREE.Mesh(geometry, material);
this.scene.add(mesh);

以上呈现:

  • 一个2D盒子
  • 设置宽度为1的不可缩放轮廓
  • 穿过盒子的一条对角线

有人可以演示如何实现2D形状的可缩放轮廓吗?我需要使用着色器吗?

1 个答案:

答案 0 :(得分:1)

我只是使用粗线示例中的代码:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setClearColor(0x000000, 0.0);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

var points = [
  -5, 4, 0, 5, 4, 0, 5, -4, 0, -5, -4, 0, -5, 4, 0
]

var geometry = new THREE.LineGeometry();
geometry.setPositions(points);

matLine = new THREE.LineMaterial({

  color: 0x00ffff,
  linewidth: 5, // in pixels
  dashed: false

});

line = new THREE.Line2(geometry, matLine);
line.computeLineDistances();
line.scale.set(1, 1, 1);
scene.add(line);

render();

function render() {
  requestAnimationFrame(render);
  matLine.resolution.set(window.innerWidth, window.innerHeight);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

<script src="https://threejs.org/examples/js/WebGL.js"></script>

<script src='https://threejs.org/examples/js/lines/LineSegmentsGeometry.js'></script>
<script src='https://threejs.org/examples/js/lines/LineGeometry.js'></script>

<script src='https://threejs.org/examples/js/lines/LineMaterial.js'></script>

<script src='https://threejs.org/examples/js/lines/LineSegments2.js'></script>
<script src='https://threejs.org/examples/js/lines/Line2.js'></script>
<script src='https://threejs.org/examples/js/lines/Wireframe.js'></script>