Threejs - Curves and Splines

by black strings

HTML

<!-- example
https://threejs.org/examples/webgl_geometry_spline_editor.html
the chordal has the most smplistic smoothing
-->

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>

CSS

/* fix mouse click offset errors when doing drags */
body {
  margin: 0;
}

JavaScript

var scene, renderer, camera;
var cube;
var controls;

var umbrellaMesh;

init();
lightSetup();
animate();

function getPerspectiveCamera(width, height){
  const cam = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
  cam.position.y = 160;
  cam.position.z = 400;
  cam.lookAt(new THREE.Vector3(0, 0, 0));
  return {cam: cam}
}

function getOrthoCamera(width, height, visualHelper = false) {
	 const cam = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 10000
   );
   
   let camH = null;
   if(visualHelper) {
  		camH = new THREE.CameraHelper(camera);
   }
   
   return {cam: cam, camH: camH}
}

function init() {
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  const width = window.innerWidth;
  const height = window.innerHeight;
  renderer.setSize(width, height);
  document.body.appendChild(renderer.domElement);

  scene = new THREE.Scene();
  var gridXZ = new THREE.GridHelper(1000, 100);
  //gridXZ.rotateX(THREE.Math.degToRad(90));
  scene.add(gridXZ);
  
  var axes = new THREE.AxesHelper(1000);
  scene.add(axes);
  
  camera = getPerspectiveCamera(width, height).cam;
  //camera = getOrthoCamera(width, height, true);
  
  scene.add(camera)
  
  controls = new THREE.OrbitControls(camera, renderer.domElement);
  lightSetup();
 	createScene();
}

function createScene() {
	const geo = new THREE.BoxGeometry( 1, 1, 1 );
  const mesh = new THREE.Mesh(geo);
  scene.add(mesh);
	displaySplineCurve();
}

// smoothness will take every X points and register it as a new curve
function pointsReduction(points, incrementalIndexForKeeps) {
	const smoothPoints = [];
  if(points && points.length > 1) {
    for(i=0; i<points.length; i+=incrementalIndexForKeeps) {
      smoothPoints.push(points[i]);
    }
    if(smoothPoints.length === 1) {
    	// push the last point if this curve only has 2 points.
    	smoothPoints.push(points[1]);
    }
    //console.log(points.length);
    //console.log(smoothPoints.length);
  } else...