Three.js动画函数传入torus参数无法正常运行问题
错误原因
你的代码问题出在requestAnimationFrame的传参逻辑错误:requestAnimationFrame接收的参数必须是函数引用,但你写的requestAnimationFrame(animate(torusToBeMoved))会在代码执行到这一行时就立刻调用animate(torusToBeMoved),把函数执行后的返回值(你的animate函数没有返回值,所以是undefined)传给requestAnimationFrame。这会直接触发无限递归,导致调用栈溢出,动画逻辑根本没法按帧正常执行。
你直接在函数内操作外部作用域的torus时,写的是requestAnimationFrame(animate),这里传的是animate函数本身的引用,符合requestAnimationFrame的参数要求,所以能正常运行。
修复方法
两种可直接替换的正确写法:
- 方法1:匿名箭头函数包装(最常用,可读性最好)
function animate(torusToBeMoved) { // 传入匿名函数作为回调,浏览器到帧时间才会执行内部逻辑 requestAnimationFrame(() => animate(torusToBeMoved)); torusToBeMoved.rotation.x += 0.01; torusToBeMoved.rotation.y += 0.005; torusToBeMoved.rotation.z += 0.01; controls.update(); renderer.render(scene, camera); }
- 方法2:用
bind绑定预设参数
function animate(torusToBeMoved) { // bind会返回绑定了指定参数的新函数引用,不会立即执行 requestAnimationFrame(animate.bind(null, torusToBeMoved)); torusToBeMoved.rotation.x += 0.01; torusToBeMoved.rotation.y += 0.005; torusToBeMoved.rotation.z += 0.01; controls.update(); renderer.render(scene, camera); }
两种写法都能保证传给requestAnimationFrame的是可执行的函数引用,同时把torus对象正确传入每一次的animate调用,动画就能正常运行了。
内容的提问来源于stack exchange,提问作者Timi Xi
相关产品推荐
相关产品推荐

