Using Web Workers for drawing using native canvas functions

前端 未结 4 791
长情又很酷
长情又很酷 2020-12-14 06:39

It\'s possible to send a CanvasPixelArray obtained via getImageData to a worker script, and let the worker script manipulate the pixels in its back

4条回答
  •  被撕碎了的回忆
    2020-12-14 07:15

    You can post the ImageData to the Web Worker, which sends the manipulated ImageData back to the caller (Main UI) thread.

    E.g.:

    1. Create a Web Worker:

      this.renderer = new Worker("renderer.js");
    2. Post the ImageData created from the canvas to the Web Worker:

      var ctx = this.canvas.getContext('2d');
      var imageData = ctx.createImageData(width, height);
      this.renderer.postMessage({ image: imageData });
    3. Do ImageData manipulation in Web Worker and post it back to Main thread:

      onmessage = function(e) {
         var processedImage = self.doImageProcessing(e.data.image);
         postMessage({ image: processedImage });
      };

    4. Set the manipulated ImageData to the canvas in the Main thread:

      this.renderer.onmessage = function (e) {
         var ctx = this.canvas.getContext('2d');
         ctx.putImageData(e.data.image, 0, 0);
      }

提交回复
热议问题