javascript - Three.js 3D cube spins faster and faster when re-initializing -
i trying understand this: first three.js example spinning 3d cube spins faster , faster every time re-initialized.
the code has init
function sets scene , animate
function starts animation loop. if repeatedly call init
, animate
, expect cube reset instead cube spinning faster , faster every time it re-initialized.
- why happening?
- isn't object being re-initialized?
- is feature of three.js or javascript?
here js fiddle shows i'm talking about. have set re-initialize every 2 seconds: http://jsfiddle.net/1hq2eslr/ (tested in firefox , chrome)
here 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 <div id="render-area"></div> var renderarea = document.getelementbyid('render-area'); // remove 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 function repeatedly increases speed of spinning cube. // global variable problem? function start() { init(); animate(); }
your previous scene isn't disposed when calling start
second time. seeing multiple scenes rendered on top of 1 , creates illusion mesh going faster. reason behind once fired, animate
keeps calling requestanimationframe(animate)
, object animate
references stays alive , not garbage collected.
to fix things, need cancel animation:
var id = null; function start() { if (id !== null) cancelanimationframe(id) ... } function animate() { id = requestanimationframe( animate ); render(); }
now objects go out of scope , garbage collector job.
Comments
Post a Comment