I am trying to understand this: The first Three.js example with a spinning 3D cube spins faster and faster every time it is re-initialized.
The code has an init function that sets up the scene and an animate function that starts the animation loop. If I repeatedly call init and animate, I expect the cube to reset completely but instead the cube is spinning faster and faster every time it it re-initialized.
- Why is this happening?
- Isn't the object being properly re-initialized?
- Is it a feature of three.js or JavaScript?
Here is a JS Fiddle that shows the what I'm talking about. I have set it up to re-initialize every two seconds: http://jsfiddle.net/1hq2esLr/ (tested in Firefox and Chrome)
Here is the full code:
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 );
// render-aread is just a <div id="render-area"></div>
var renderarea = document.getElementById('render-area');
// Remove 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 );
}
// Calling this function repeatedly increases the speed of the spinning cube.
// Global variable problem?
function start() {
init();
animate();
}