Threejs - starter

by black strings

HTML

<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 controls;

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

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

  scene = new THREE.Scene();
   scene.rotation.x = -Math.PI / 2;
  
  var gridXZ = new THREE.GridHelper(1000, 100);
  scene.add(gridXZ);
  gridXZ.rotation.x = -Math.PI / 2;
 

  var axes = new THREE.AxesHelper(1000);
  scene.add(axes);

  camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
  camera.position.y = 160;
  camera.position.z = 400;
  camera.lookAt(new THREE.Vector3(0, 0, 0));

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  
  /* var points = [new THREE.Vector3(0, 30, 0)];
  
  for(var point of points) {
        createSphere(point, 0xffff00);
  } */
}

function animate() {
  controls.update();
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function lightSetup() {
  if (scene) {
    var dirLight = new THREE.DirectionalLight();
    dirLight.position.set(3, 2, 1);
    dirLight.position.multiplyScalar(10);
    scene.add(dirLight);
  }

}

function createSphere(position, color) {
	const geometry = new THREE.SphereGeometry( 10, 52, 52 );
const material = new THREE.MeshBasicMaterial( { color: color } );
const sphere = new THREE.Mesh( geometry, material );
sphere.position.copy(position);
scene.add( sphere );
}

function printVector3(vector) {
	console.log(vector.x + " " + vector.y + " " + vector.z);
}

function transformVector3sToVector2s(vector3s) {
		let vector2s = null;
		if(vector3s) {
			vector2s = vector3s.map((v) => {
				return new THREE.Vector2(v.x, v.y);
			});
		} else {
			throw new Error(`Cannot transform Vector3s to Vector2s: the vectors array is null or undefined.`);
		}
		return vector2s;
	}