Search code examples
three.js3dgeometrypolygonbuffer-geometry

how to draw polygon in three js using vertices?


I have vertices(x,y,z) of a polygon as input. How can I render a polygon having these vertices in three.js? THREE.Geometry() is removed from three js. how to draw plane polygon with bufferGeometry or any other method ? now when i draw polygon with vertices it drawing incomplete mesh (polygon). following code is used to draw polygon.

const verticesGeometry = new THREE.BufferGeometry().setFromPoints(measurement.coordinates.map((coord) => new THREE.Vector3(coord.x, coord.y, coord.elevation)))
const polygon  = new THREE.Mesh(verticesGeometry , new THREE.MeshBasicMaterial({ color: measurement.color, side: THREE.DoubleSide}))
scene.add(polygon)

screenshots attached of issue, which is i am facing right now, (3 points polygon working perfectly, more than it, rendering incomplete.) thanks in advance. enter image description here

i also tried THREE.ShapeGeometry() but polygon are rendering to the bottom because THREE.shape() is accepting only VECTOR2 points.i am passing vector3 but it neglecting 3rd (z) point.

 let polyShape = new THREE.Shape(measurement.coordinates.map((coord) => 
 new THREE.Vector3(coord.x, coord.y, coord.elevation)))
const geometry = new THREE.ShapeGeometry( polyShape )
let polygon = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: measurement.color, side: THREE.DoubleSide }))

see the below image for reference. enter image description here


Solution

  • As per the @berthur answer I tried following code and it worked. Thanks to https://stackoverflow.com/users/10559142/berthur

    let coordinates = [
     {
       x : 1,
       y : 1,
       elevation : 10
     },
     {
       x : 2,
       y : 1,
       elevation : 10
     },
     {
       x : 2,
       y : 2,
       elevation : 10
     },
     {
       x : 1,
       y : 2,
       elevation : 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.elevation]).flat(), 3))
    let polygon = new THREE.Mesh(polyGeometry, new THREE.MeshBasicMaterial({ color: "ColorYouWant, side: THREE.DoubleSide}))
    scene.add(polygon);