Reputation: 7468
I have vertices(x,y,z coords) of a polygon as input. How can I render a polygon having these vertices in three.js?
There is this documentation.But it seems to involve bezier. I need simple straight edged polygon.
Upvotes: 2
Views: 6889
Reputation: 5666
I also need this and while the answer of @Aakash helped me to start, setting the points in the ShapeGeometry was a problem
Just
Shape
object with the 2D coordinates (Vector2
)Mesh
from that Geometry and the Material
you wantPerfect example for it is https://threejs.org/examples/webgl_geometry_shapes
Especially have a look at the californiaShape
object and the addShape
function
const californiaPts = [];
californiaPts.push( new THREE.Vector2( 610, 320 ) );
californiaPts.push( new THREE.Vector2( 450, 300 ) );
californiaPts.push( new THREE.Vector2( 392, 392 ) );
...
const californiaShape = new THREE.Shape( californiaPts );
addShape( californiaShape, ... );
function addShape( shape, extrudeSettings, color, x, y, z, rx, ry, rz, s ) {
let geometry = new THREE.ShapeGeometry( shape );
mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: color, side: THREE.DoubleSide } ) );
mesh.position.set( x, y, z - 125 );
mesh.rotation.set( rx, ry, rz );
mesh.scale.set( s, s, s );
...
}
Upvotes: 1
Reputation: 882
You can create a polygon from vertices with the following code:
var geom = new THREE.Geometry();
var v1 = new THREE.Vector3(0,0,0);
var v2 = new THREE.Vector3(0,500,0);
var v3 = new THREE.Vector3(0,500,500);
geom.vertices.push(v1);
geom.vertices.push(v2);
geom.vertices.push(v3);
geom.faces.push( new THREE.Face3( 0, 1, 2 ) );
geom.computeFaceNormals();
var object = new THREE.Mesh( geom, new THREE.MeshNormalMaterial() );
scene.add(object);
Copy and paste this code in and then change x, y, and z coordinates of v1, v2, and v3 (or however many vertices you need) to the coordinates of your vertices.
Essentially, you are creating vertices using THREE.Vector3
to supply the coordinates and then pushing them to the vertices property of an empty THREE.Geometry()
;
Code is from this answer
Upvotes: 4
Reputation: 313
THREE.Geometry
is removed, try the following method
let coordinates = [
{
x : 1,
y : 1,
z: 10
},
{
x : 2,
y : 1,
z: 10
},
{
x : 2,
y : 2,
z: 10
},
{
x : 1,
y : 2,
z: 10
}
]
let polyShape = new THREE.Shape(coordinates.map((coord) => new THREE.Vector2(coord.x, coord.y)))
const polyGeometry = new THREE.ShapeGeometry(polyShape);
polyGeometry.setAttribute("position", new THREE.Float32BufferAttribute(coordinates.map(coord => [coord.x, coord.y, coord.z]).flat(), 3))
let polygon = new THREE.Mesh(polyGeometry, new THREE.MeshBasicMaterial({ color: "colorYOuWant", side: THREE.DoubleSide}))
scene.add(polygon);
Upvotes: 1