three.js - 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;
};
}
我想在点击时停止动画,但我还没有成功。
我错过了什么?
谢谢
解决方案
您必须使用上次通话返回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>
推荐阅读
- node.js - 为什么我的 React.js 和 Node.js 应用程序有时会返回“404 not found”,但大多数时候它都可以工作?
- ruby - 来自 DB 的字符串为 \\xC3\\xB6 但我需要实际字符“ö”才能写入 CSV
- java - 验证..让我发疯
- android - 如何从 onResume 调用 onMapReady()
- java - 无法流式传输 JSON 数组
- google-cloud-platform - Cloud Build GitHub App 只绑定一个 GCP 项目?
- python-3.x - 为 python 3 安装 VTK
- joomla - 对 Joomla 实时站点的更改
- ios - iOS Swift Core Data 如何从 NSFetchedResultsController 中搜索 FetchedObjects
- javascript - 将数据加载到输入字段:JQuery