Tom Stowell Tom Stowell - 2 months ago 18
Javascript Question

Simple Cube - Three JS

I've been trying to achieve a simple rotating 3D cube via the Three.js library for WebGL.

I can't seem to identify any faults in my code when compared to the masses of tutorials out there, however all I see is a black screen with no geometry.



//Define window size
var width = window.innerWidth;
var height = window.innerHeight;

//smoothened edges for the renderer defined
var renderer = new THREE.WebGLRenderer({antialias:true});
//renderer size
renderer.setSize(width,height);
//renderer is appended to the html document
document.body.appendChild(renderer.domElement);

var scene = new THREE.Scene;

//Add 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);

//Rotate cube 45 degrees
cube.rotation.y=Math.PI*45/180;

//Add cube to scene
scene.add(cube);

//Add Camera - FOV, Ratio, Close, Far
var camera = new THREE.PerspectiveCamera(45,width/height,0.1,10000);

//Position camera
camera.position.y = 160;

//Higher the z value, the closer to the camera/user
camera.position.z = 400;

//Camera pointed towards cube
camera.lookAt(cube.position);

//Add camera to scene
scene.add(camera);

//Define 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);

//Render scene
function render() {
render.render(scene,camera);

var clock = new THREE.Clock;

//rotate cube clockwise - subtract time passed from rotation
cube.rotation.y -=clock.getDelta();

requestAnimationFrame(render);
}

//Call 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 linking to Three.js via the CDN found on Google Developer links found here: https://developers.google.com/speed/libraries/

Any help would be much appreciated.

Many thanks
Tom

Answer

There is a tiny typo in your JS code at line 55:

render.render(scene,camera);

should be:

renderer.render(scene,camera);

Next time I highly recommend opening up your browser's console, the error was logged the already, so fixing the bug was very straightforward.


Besides of that, your code works just fine. The cube rotates, although it's very slow. You may want to adjust line 60 to make it rotate faster (eg. by multiplying the value by 100).

Comments