Search code examples
htmlcanvasgetimagedata

Speeding up a canvas image crop


I'm working on a simple image crop where the user draws a line with the mouse around an area that they want to keep. When they confirm, the rest of the image will be cropped out. Here's how I'm currently handling said cropping:

var data = c.getImageData(0,0,canvas.width,canvas.height);      
for (var x = 0; x < data.width; x++) {
   for (var y = 0; y < data.height; y++) {
      if (!c.isPointInPath(x,y)) {
         var n = x + (data.width * y);
         var index = n*4; 
         data.data[index+3] = 0;
      }
   }
}

However, this can bog down really quickly. The less of the image you try to retain, the faster it goes, but even saving 30% of the image (canvas is 800x800) causes it to hang for several seconds. Is there a faster way to go about this?


Solution

  • There is no real way to speed it up when you have to use a user defined shape, but the bogging down can be handled with a worker.