Skip to content

Commit

Permalink
Merge pull request #391 from webgpu/worker-update
Browse files Browse the repository at this point in the history
Remove React guard from worker sample
  • Loading branch information
toji authored Mar 11, 2024
2 parents 78b57b3 + 5bd5d12 commit c7e7f34
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 c7e7f34

Please sign in to comment.