Curve Visualization & Distance

by black strings

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.js"></script>
<p>
You can calc the distance of the curve by adding all the linear segements. To get a distance from start of curve to a point on the curve requires a bit more setup. You have to obtain a point on the curve which can be retrieved 2 ways. Either pass a number between 0-1 to the curve api or use a line/ray intersection check to get an intersection on the curve.
</p>
<p>
The more points on the curve, the more accurate the distance is, just add enough points to get to your satisfy precision, but don't add too much unnecessary points. The larger the curve too, the more points you may need to add for accuracy.
</p>

CSS

body {
	margin: 0;
}
p {
  font-size: .7rem;
}
canvas {
	display: block;
}

JavaScript

const scene = new THREE.Scene();

const axis = new THREE.AxesHelper(10);
//scene.add(axis);

const camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 40;

// create a math curve
const bezierCurveAnchorPoints = [
new THREE.Vector3( -10, -5, 0 ),
	new THREE.Vector3( -5, 10, 0 ),
	new THREE.Vector3( 0, -10, 0 ),
	new THREE.Vector3( 5, 5, 0 )
];
const cubicBezierCurve = new THREE.CubicBezierCurve3(...bezierCurveAnchorPoints);


// visualize the test Line to intersect with the curve
let startX = 0;
let startY = 0;
let endX = 6;
let endY = 1.5;
const lineStart = new THREE.Vector3(startX, startY);
const lineEnd = new THREE.Vector3(endX, endY);
drawLine(lineStart, lineEnd);

const testLine = new THREE.Line3(lineStart, lineEnd);
const intersectFound = findIntersectionLineWithCurve(testLine, cubicBezierCurve);
if(intersectFound && intersectFound.intersection) {
  const intersectPointTest = createSphereMesh(.4, 0xff00ff);
  intersectPointTest.position.copy(intersectFound.intersection);
  console.log('distance along path using line intersection to curve, ', intersectFound.distanceAlongPath);
  // getLength
  console.log('total curve distance,', cubicBezierCurve.getLength());
}


// visualize math curve into geometry mesh
const smoothness = 10;
//const curvePoints = cubicBezierCurve.getPoints(smoothness);
const curvePoints = cubicBezierCurve.getSpacedPoints(smoothness);
const geometry = new THREE.BufferGeometry().setFromPoints(curvePoints);
const material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
const curveObject = new THREE.Line( geometry, material );
scene.add( curveObject );

// visualize curve's spaced points 
const sphereGeomtry = new THREE.SphereBufferGeometry( 0.1 );
const sphereMaterial = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const spacedPoints = cubicBezierCurve.getSpacedPoints( 10 );
//const spacedPoints = cubicBezierCurve.getPoints( 10 );

for ( let point of spacedPoints )...