developit / greenlet

🦎 Move an async function into its own thread.
https://npm.im/greenlet
4.67k stars 100 forks source link

Add OffscreenCanvas to transferables #54

Closed marcbouchenoire closed 2 years ago

marcbouchenoire commented 3 years ago

This PR:

marcbouchenoire commented 3 years ago

If others encounter this PR, I've published these changes as a fork to https://npm.im/@bouchenoiremarc/greenlet with version 1.1.1, in the meantime this lands.

jcbhmr commented 1 year ago

Hello! 👋 I'm interested in this feature. I would like to use canvas.transferControlToOffscreen() with greenlet. @developit or @marcbouchenoire is there a reason that this PR was closed? I notice it was open for 7ish months. Here's the gist of what I'm trying to do. Yes, I could just use the main thread to do this 🙄 but I want to use a worker just because! 😅

// this doesn't work right now 😢
const f = greenlet(async (offscreenCanvas) => {
  const ctx = offscreenCanvas.getContext("2d")
  const mouseChannel = new BroadcastChannel("mouseChannel")
  // do async rendering loop stuff on worker thread
  // with the mouse position. takes ~2s for animation to
  // be done
})
// async takes two seconds; graphic animation outsourced
// to worker thread!
await f(canvas.transferControlToOffscreen())

On a related note, it might be good to also consider checking for ReadableStream, WritableStream, and TransformStream as they appear to be on the list of transferable objects from MDN: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects#supported_objects