reactjs - 与 React 一起使用时未调用 requestAnimationFrame 回调
问题描述
我正在尝试用反应组件包装画布组件并设置 requestAnimationFrame 以便能够在画布上绘制动画。
我有一个简单的组件,它试图简单地画一个圆圈:
import * as React from "react";
import { useLayoutEffect, useRef } from "react";
export interface Props {}
export const Loop: React.FC<Props> = () => {
const cv = useRef<HTMLCanvasElement>(null);
const oldTimestamp = useRef<number>(0);
useLayoutEffect(() => {
let animationID = 0;
console.log("USEEFFECT");
const loop = (timestamp: number) => {
let secondsPassed = (timestamp - oldTimestamp.current) / 1000;
secondsPassed = Math.min(secondsPassed, 0.1);
oldTimestamp.current = timestamp;
console.log("LOOP");
update(secondsPassed);
draw();
animationID = requestAnimationFrame(loop);
};
animationID = requestAnimationFrame(loop);
return cancelAnimationFrame(animationID);
}, []);
const update = (secondsPassed: number) => {};
const draw = () => {
console.log("DRAW");
const ctx = cv && cv.current && cv.current.getContext("2d");
if (ctx) {
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
}
};
return (
<div>
<canvas ref={cv}></canvas>
</div>
);
};
我添加了三个console.log
电话来帮助确定正在发生的事情。仅 ATMconsole.log("USEEFFECT");
被记录,但没有其他内容。在我看来,animationID = requestAnimationFrame(loop);
inuseLayoutEffect
没有调用loop
回调。
我认为中的requestAnimationFrame
设置useLayoutEffect
是正确的。
我做错了什么?
解决方案
您立即取消动画帧,而是应该返回函数:
return () => cancelAnimationFrame(animationID)