Skip to content

Commit

Permalink
Remove React guard from worker sample
Browse files Browse the repository at this point in the history
Removes some code from the worker sample that only existed to catch
errors when the code was executed twice by React. Now that React
has been removed it's no longer necessary.
  • Loading branch information
toji committed Mar 11, 2024
1 parent 78b57b3 commit 5bd5d12
Showing 1 changed file with 13 additions and 21 deletions.
34 changes: 13 additions & 21 deletions sample/worker/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,17 @@ worker.addEventListener('message', (ev) => {
}
});

try {
// In order for the worker to display anything on the page, an OffscreenCanvas must be used.
// Here we can create one from our normal canvas by calling transferControlToOffscreen().
// Anything drawn to the OffscreenCanvas that call returns will automatically be displayed on
// the source canvas on the page.
const offscreenCanvas = canvas.transferControlToOffscreen();
const devicePixelRatio = window.devicePixelRatio;
offscreenCanvas.width = canvas.clientWidth * devicePixelRatio;
offscreenCanvas.height = canvas.clientHeight * devicePixelRatio;
// In order for the worker to display anything on the page, an OffscreenCanvas must be used.
// Here we can create one from our normal canvas by calling transferControlToOffscreen().
// Anything drawn to the OffscreenCanvas that call returns will automatically be displayed on
// the source canvas on the page.
const offscreenCanvas = canvas.transferControlToOffscreen();
const devicePixelRatio = window.devicePixelRatio;
offscreenCanvas.width = canvas.clientWidth * devicePixelRatio;
offscreenCanvas.height = canvas.clientHeight * devicePixelRatio;

// Send a message to the worker telling it to initialize WebGPU with the OffscreenCanvas. The
// array passed as the second argument here indicates that the OffscreenCanvas is to be
// transferred to the worker, meaning this main thread will lose access to it and it will be
// fully owned by the worker.
worker.postMessage({ type: 'init', offscreenCanvas }, [offscreenCanvas]);
} catch (err) {
// TODO: This catch is added here because React will call init twice with the same canvas, and
// the second time will fail the transferControlToOffscreen() because it's already been
// transferred. I'd love to know how to get around that.
console.warn(err.message);
worker.terminate();
}
// Send a message to the worker telling it to initialize WebGPU with the OffscreenCanvas. The
// array passed as the second argument here indicates that the OffscreenCanvas is to be
// transferred to the worker, meaning this main thread will lose access to it and it will be
// fully owned by the worker.
worker.postMessage({ type: 'init', offscreenCanvas }, [offscreenCanvas]);

0 comments on commit 5bd5d12

Please sign in to comment.