spite / ccapture.js

A library to capture canvas-based animations at a fixed framerate
MIT License
3.59k stars 407 forks source link

Usage with React: .start() causes window.requestAnimationFrame to stop working. #133

Closed dwjohnston closed 2 years ago

dwjohnston commented 2 years ago

I have a repro for this here:

https://github.com/dwjohnston/ccapture-test

I am trying to do a very basic use of this in React.

Here's my example code:

// I have the min.js file imported in the head, so CCapture will be exposed globally. 

function App() {

  const canvasRef = useRef<null | HTMLCanvasElement>(null);

  // Set up a reference to CCapture
  //@ts-ignore
  const capturerRef = useRef(new CCapture({
    format: "webm"
  }));

  useEffect(() => {
    const context = canvasRef.current?.getContext('2d');

    if (context) {

      // Standard recursive loop for drawing animation frame 
      const draw = () => {
        context.strokeRect(randInt(), randInt(), randInt(), randInt())
        window.requestAnimationFrame(draw);
      };

      window.requestAnimationFrame(draw);
    }

  }, []);

  return (
    <div className="App">

      // Call start
      <button onClick={() => {
        //@ts-ignore
        capturerRef.current.start();
      }}>start </button>

      <button onClick={() => {
        //@ts-ignore
        capturerRef.current.stop();

      }}> stop </button>

      <canvas ref={canvasRef} width="500" height="500"></canvas>

    </div>
  );
}

export default App;

When you press the start button (and call capturer.start) window.requestAnimationFrame stops working.

Any idea why this is?

dwjohnston commented 2 years ago

This appears not to be a React specific thing, I've reproduced the same thing in vanilla:

https://github.com/dwjohnston/ccapture-test/tree/no-react

Nope: calling the capture method seems like it is definitely required to keep the animation displaying:

https://github.com/dwjohnston/ccapture-test/commit/151433c0750478591c9b18874bb4ae7693ebe31d

dwjohnston commented 2 years ago

Aaaand fixed, works fine with React.

https://github.com/dwjohnston/ccapture-test/commit/25cdafdbbf357ed69f4e876a646d3a4f1364c6b9

Feel free to use this as an example.

Great library!