I'm puzzled by a phenomenon with the first Three.js example: the spinning 3D cube spins faster and faster every time it is re-initialized.
The code consists of an init
function that sets up the scene and an animate
function that kicks off the animation loop. Despite my expectation that the cube should reset completely when I repeatedly call init
and animate
, it actually spins faster each time it is re-initialized.
- What could be causing this?
- Is the object not properly re-initialized?
- Is this a feature of three.js or JavaScript?
Check out this JS Fiddle demonstration of the issue, where the cube is re-initialized every two seconds: http://jsfiddle.net/1hq2esLr/ (tested in Firefox and Chrome)
Below is the complete code snippet:
var camera, scene, renderer,
geometry, material, mesh;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
geometry = new THREE.BoxGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
// The render area is simply a <div id="render-area"></div>
var renderarea = document.getElementById('render-area');
// Clear all existing nodes.
while (renderarea.firstChild) {
renderarea.removeChild(renderarea.firstChild);
}
renderarea.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
// Repeatedly calling this function seems to accelerate the spinning cube. Could this be due to a global variable issue?
function start() {
init();
animate();
}