My goal was to create a simple rotating 3D cube using the Three.js library for WebGL.
Despite following numerous tutorials, I can't figure out why my code only displays a black screen with no geometry.
//Setting window dimensions
var width = window.innerWidth;
var height = window.innerHeight;
//Creating renderer with smooth edges
var renderer = new THREE.WebGLRenderer({antialias:true});
//Adjusting size of renderer
renderer.setSize(width,height);
//Appending renderer to HTML document
document.body.appendChild(renderer.domElement);
var scene = new THREE.Scene;
//Adding Cube - width, height, depth
var cubeGeom = new THREE.CubeGeometry(100,100,100);
var cubeMaterial = new THREE.MeshLambertMaterial({color:0x1ec876});
var cube = new THREE.Mesh(cubeGeom,cubeMaterial);
//Rotating cube by 45 degrees
cube.rotation.y=Math.PI*45/180;
//Adding cube to scene
scene.add(cube);
//Adding Camera - FOV, Ratio, Near, Far
var camera = new THREE.PerspectiveCamera(45,width/height,0.1,10000);
//Positioning camera
camera.position.y = 160;
//Bringing camera closer
camera.position.z = 400;
//Pointing camera towards cube
camera.lookAt(cube.position);
//Adding camera to scene
scene.add(camera);
//Defining skyBox
var skyBoxGeom = new THREE.CubeGeometry(10000, 10000, 10000);
var skyBoxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
var skyBox = new THREE.Mesh(skyBoxGeom,skyBoxMaterial);
scene.add(skyBox);
//Point Light
var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0,300,200);
scene.add(pointLight);
//Rendering scene
function render() {
render.render(scene,camera);
var clock = new THREE.Clock;
//Rotating cube clockwise - subtracting time passed from rotation
cube.rotation.y -=clock.getDelta();
requestAnimationFrame(render);
}
//Calling render function
render();
canvas {
position: fixed;
top:0;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
p.s. I am using the CDN link to Three.js provided by Google Developers: https://developers.google.com/speed/libraries/
Your assistance is greatly appreciated.
Thank you, Tom