首页 > 解决方案 > THREE.js - 点击时停止动画

问题描述

    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; 
        };
    }

我想在点击时停止动画,但我还没有成功。

我错过了什么?

谢谢

标签: three.js

解决方案


您必须使用上次通话返回cancelAnimationFrame()的相同通话。你实际上并没有在你的代码中这样做。请看以下演示停止动画循环的基本工作流程的实时示例。requestIDrequestAnimationFrame()

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>


推荐阅读