Search code examples
three.jsgeometrypolyline

How can I draw polyline in three.js?


I would like to draw a polyline(using x, y values) to create a shape. For example, when you draw a polyline with a set of coordinates -(0,0), (0,2), (2,0), (0,0), it will create a rectangular shape. How could I do it in three.js ?

And, after drawing a shape using polyline, could I give a height (z value) to the shape and make it 3D ?

Thanks.


Solution

  • Depends on what you really want. As you want a polyline, not a curve.

    Based on THREE.Shape() and this example:

    var points = [
      new THREE.Vector2(0, 0),
      new THREE.Vector2(2, 0),
      new THREE.Vector2(2, 2),
      new THREE.Vector2(0, 2)
    ];
    var shape = new THREE.Shape(points);
    shape.autoClose = true; // the shape will be closed automatically, thus we don't need to put the fifth point
    var geometry = shape.createPointsGeometry();
    var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({color: "yellow"}));
    scene.add(line);
    

    Based on THREE.Geometry():

    var points3D = new THREE.Geometry();
    points3D.vertices.push( // here you can use 3-dimensional coordinates
      new THREE.Vector3(0, 0, 0.5),
      new THREE.Vector3(2, 0, 1),
      new THREE.Vector3(2, 2, 2),
      new THREE.Vector3(0, 2, 3),
      new THREE.Vector3(0, 0, 0.5) // there is no autoClose function here, thus we need the fifth point
    );
    var line2 = new THREE.Line(points3D, new THREE.LineBasicMaterial({color: "red"}));
    scene.add(line2);
    

    jsfiddle example with both solutions