使用JavaScript画线 | Drawing Lines with JavaScript
在本指南中,我们将展示如何使用Verge3D API创建和渲染线条。
Thin Lines
细线更容易创建,但由于WebGL的限制,线宽不能超过1像素。要绘制此类线条,首先需要定义一个 LineBasicMaterial 材质。
// create a blue LineBasicMaterial
const material = new v3d.LineBasicMaterial({ color: 0x0000ff });
设置材质之后,我们需要一个带有一些顶点的几何体:
const points = [];
points.push(new v3d.Vector3(-10, 0, 0));
points.push(new v3d.Vector3( 0, 10, 0));
points.push(new v3d.Vector3( 10, 0, 0));
const geometry = new v3d.BufferGeometry().setFromPoints(points);
注意,线条在每对连续的顶点之间绘制,但不会在第一个和最后一个顶点之间绘制(线条不是闭合的)。
现在我们有了两条线的点和一个材质,可以把它们放在一起形成一条线:
const line = new v3d.Line(geometry, material);
剩下的就是将其添加到场景中。
app.scene.add(line);
您现在应该可以看到一个由两条蓝线构成的向上指向的箭头。
Thick Lines
粗线由 MeshLine 或 MeshLineIndexed 类创建,具体取决于您提供的源数据。与细线类似,它们需要一种特殊的材质,称为 MeshLineMaterial。
// create a blue MeshLineMaterial
const material = new v3d.MeshLineMaterial({ color: 0x0000ff, lineWidth: 0.3 });
lineWidth 是线条在世界单位中的绝对宽度,而非像素大小。
要生成具有三角化几何体的线条,您需要将一些点传递给 MeshLineIndexed。
const points = [];
points.push(new v3d.Vector3(-10, 0, 0));
points.push(new v3d.Vector3( 0, 10, 0));
points.push(new v3d.Vector3( 10, 0, 0));
const geometry = new v3d.BufferGeometry().setFromPoints(points);
const line = new v3d.MeshLineIndexed();
line.fromBufferGeometry(geometry);
好处是,这种几何体可以与常规的 Mesh 对象一起使用:
const mesh = new v3d.Mesh(line.geometry, material);
将此网格添加到场景中,您将看到相同的箭头,但线条更粗:
app.scene.add(mesh);
另请参阅
LineHTML 类可用于在3D对象和HTML元素之间绘制线条。