var thisframe;
(function animate() {
thisframe = requestAnimationFrame(animate);
renderer2.render(scene, cam2);
terminate();
})();
function terminate() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
var myReq = requestAnimationFrame;
var stoprender = document.getElementById( 'stoprenderbtn' );
stoprender.onclick = function StopAnimation() {
alert("thisbuttonworks"); # thisbuttonworks
cancelAnimationFrame(myReq);
return;
};
}
我想在单击时停止动画,但是还没有成功。
我想念什么?
谢谢
答案 0 :(得分:1)
您必须使用上次cancelAnimationFrame()
调用返回的requestID
来调用requestAnimationFrame()
。您实际上没有在代码中执行此操作。看下面的实时示例,该示例演示了停止动画循环的基本工作流程。
var camera, scene, renderer;
var geometry, material, mesh;
var requestID;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
document.getElementById( 'stopAnimation' ).addEventListener( 'click', stopAnimation );
}
function animate() {
requestID = requestAnimationFrame( animate );
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
function stopAnimation() {
cancelAnimationFrame( requestID );
}
body {
margin: 0;
}
canvas {
display: block;
}
button {
position: absolute;
}
<script src="https://threejs.org/build/three.js"></script>
<button id="stopAnimation">
Stop Animation
</button>