Search code examples
three.jsline

Three JS - why is line length equal to zero?


New to three js. Exploring working with line segments. I'm trying to determine the length of a line. I'm using the computeLineDistances(); method to get the line length. The line is drawn along the x-axis ending at x=10. For some reason the log console returns a zero value. Does anyone have an explanation why the length returned in the console = 0;

var myLength =0 ;

//a line start point (0,0,0), end point (10,0,0)
var points = []; // x, y, z
points.push( new THREE.Vector3( 0,  0, 0 ) ); // start point
points.push( new THREE.Vector3( 10, 0, 0 ) ); 

var geometry = new THREE.BufferGeometry().setFromPoints( points );

var axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );

drawLine(); //call the line drawing function

// function to draw a line
function drawLine () {
    
var line = new THREE.Line( geometry, material );

scene.add( line );
//var myLength = line.distanceTo();
var myLength = line.computeLineDistances();

//return (line);

} // end function drawLine

//log
console.log("myLength: ", myLength);

Below is the fiddle link:

https://jsfiddle.net/kdwoell/kgm6j1q4/


Solution

  • If you want to know the total length of line, then, after calling .computeLineDistances() on a non-indexed buffer geometry, you can get it from:

    line.geometry.attributes.lineDistance.array[ length_of_points_array - 1]

    or

    line.geometry.attributes.lineDistance.getX(line.geometry.attributes.lineDistance.count - 1);

    shortly:

    var ld = line.geometry.getAttribute("lineDistance");
    console.log(ld.getX(ld.count - 1));
    

    Example:

    body {
      overflow: hidden;
      margin: 0;
    }
    <script type="module">
    import * as THREE from "https://threejs.org/build/three.module.js";
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
    camera.position.set(0, 0, 20);
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(innerWidth, innerHeight);
    document.body.appendChild(renderer.domElement);
    
    var pts = [
      new THREE.Vector3(0, 0, 0),
      new THREE.Vector3(10, 0, 0),
      new THREE.Vector3(10, 10, 0)
    ];
    var geom = new THREE.BufferGeometry().setFromPoints(pts);
    var mat = new THREE.LineBasicMaterial({color: "yellow"});
    var line = new THREE.Line(geom, mat);
    line.computeLineDistances();
    
    var ld = line.geometry.getAttribute("lineDistance");
    console.log("line's total length: " + ld.getX(ld.count - 1));
    
    scene.add(line);
    
    renderer.setAnimationLoop(()=>{
      renderer.render(scene, camera);
    });
    </script>