Skip to content

Instantly share code, notes, and snippets.

@RxET
Created March 20, 2018 04:48
Show Gist options
  • Save RxET/b08aac9a752bc3f8805915bae637cf0d to your computer and use it in GitHub Desktop.
Save RxET/b08aac9a752bc3f8805915bae637cf0d to your computer and use it in GitHub Desktop.
Three.js or There’s a hypercube in my timeline and I can’t get out
window.addEventListener('load', setUp, false);
function setUp() {
// scene, camera, and renderer
makeScene();
// add an object
createBox();
// and a light
letThereBeLight();
}
//declare these variables in the global scope so our respective functions have access to them later
var scene;
var camera;
var box;
var renderer;
var controls;
function makeScene() {
//get browser width and height
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
// make a scene
scene = new THREE.Scene();
// and a camera
var aspectRatio = WIDTH / HEIGHT;
var fieldOfView = 75;
var near = 0.5;
var far = 1000;
camera = new THREE.PerspectiveCamera(
fieldOfView,
aspectRatio,
near,
far
);
camera.position.z = 5;
// create the renderer
renderer = new THREE.WebGLRenderer({alpha: true});
// and set its size to the dimensions of the window
renderer.setSize(WIDTH, HEIGHT);
// then attach the renderer to the div container in your HTML file
var threeContainer = document.getElementById('threeContainer');
threeContainer.appendChild(renderer.domElement);
}
function createBox() {
//create the box geometry
var boxGeometry = new THREE.BoxGeometry( 1, 1, 1 );
//create the material, this one is purple and affected by lights
var boxMaterial = new THREE.MeshPhongMaterial( { color: 0xa35ae5 } )
//smash them together in a mesh, and add to your scene
box = new THREE.Mesh(boxGeometry, boxMaterial);
scene.add(box);
}
function letThereBeLight() {
//create your light - this one is white at almost full intensity
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.9 );
// set the light direction
directionalLight.position.set(150, 350, 350);
//let it cast shadows
directionalLight.castShadow = true;
// and add it to the scene
scene.add( directionalLight );
controls = new THREE.OrbitControls(camera, renderer.domElement)
animate();
}
function animate() {
//keep calling our animate function to keep the motion flowing
requestAnimationFrame( animate );
//finally render our scene
renderer.render( scene, camera );
//give our box a little twist
box.rotation.x += 0.01;
box.rotation.y += 0.01;
//and update our camera controls for each frame
controls.update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment