简体   繁体   中英

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.

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);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM