I am using offscreencanvas (https://threejs.org/manual/#en/offscreencanvas) to render react-three-fiber elements on a separate thread. There are not a lot of resources about this on the internet (however I found this issue: https://github.com/pmndrs/react-three-fiber/issues/280). I tried reproducing it but I get an error.
Main thread create canvas:
// main.jsx (main thread)
import React from "react";
export const Main = () => {
const canvasRef = React.useRef();
React.useEffect(() => {
const offscreen = canvasRef.current.transferControlToOffscreen();
const worker = new Worker('worker.js');
worker.postMessage({
canvas: offscreen,
}, [offscreen])
}, []);
return (
<canvas ref={canvasRef} />
);
}
Separate thread:
// worker.jsx (worker thread)
import { render } from 'react-three-fiber';
import { WebGLRenderer, Scene, PerspectiveCamera } from 'three';
self.onmessage = (event) => {
const { canvas } = event.data;
const scene = new Scene();
const renderer = new WebGLRenderer({ canvas });
const camera = new PerspectiveCamera( 75, canvas.width / canvas.height, 0.1, 1000 );
render(<gridHelper scale={[10, 10, 10]}/>, scene);
renderer.render(scene, camera);
}
When I render this, I get an error saying "Cannot read property of undefined". Could anyone help me identify why I get this error? Or provide a demo using offscreencanvas with react-three-fiber?
Demo: https://f-loat.github.io/offscreen-canvas-demo
GitHub: https://github.com/F-loat/offscreen-canvas-demo