Search code examples
javascripthtml5-canvases6-promiseweb-workeroffscreen-canvas

Send message from webworker and wait for reply


I am currently working with webworker and canvas for the first time and have a question about it.

I have a webpage that needs to draw multiple elements on a canvas. When the canvas is full I want to create a new canvas and continue drawing on it. I have outsourced the logic for drawing to a webworker that gets a list of elements and the current canvas (OffscreenCanvas). I would like to use a promise to send a message to the frontend in the webworker to create the new canvas and get it back as a response. Is there an elegant solution for this? I seem to have hit a block in my thinking.


Solution

  • I think i found a solution:

    const WEBWORKER_INSTANCE = self; // DedicatedWorkerGlobalScope
    const PROMISE_TIMEOUT = 1000;
    
    function addNewPageCallback(pageCount: number): Promise<OffscreenCanvas> {
      return new Promise<OffscreenCanvas>((resolve, reject) => {
        let timeoutId = null;
        const id = `page#${pageCount + 1}`;
    
        WEBWORKER_INSTANCE.addEventListener('message', (event: MessageEvent<DrawCanvasEvent>) => {
          if (event.data.action === 'page-added') {
            const data = event.data as DrawCanvasAddPageResponseEvent;
            if (data.id === id) {
              clearTimeout(timeoutId);
              resolve(data.canvas);
            }
          }
        });
    
        const message: DrawCanvasAddPageRequestEvent = {
          action: 'add-page',
          id
        };
        postMessage(message);
    
        timeoutId = setTimeout(reject, PROMISE_TIMEOUT);
      });
    }