1

If you click Run code snippet in this link, it shows a cool usage of <canvas> where you can "cut-out" part of the image (just drag your mouse on the image to "cut"). I'm just curious if there is any way to save the resulting "cut-out" part of the image, as a transparent PNG (i.e. everything that is white in the canvas would be transparent).

If anyone can point me in the right direction (or tell me it's not doable), I'd appreciate it.

Community
  • 1
  • 1
user3304303
  • 1,027
  • 12
  • 31

2 Answers2

0

Yes, there is a way. Use canvas context.getImageData to get image raw data-array. Do with it(raw data) what you need(make transparent any pixel you need), and then use context.putImageData to render data on canvas. Then use var data = canvas.toDataURL("image/png") to get image data. And then you can do so: image.src = data; Use this link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData for more info

Dmitriy
  • 3,745
  • 16
  • 24
0

Here's a quick tour showing how to crop & save a user-dragged cutout of an image:

  1. Draw the image on the canvas.
  2. Listen to mouse events and let the user define the region they want to cut out by continuously connecting new lines to the current mouse position.
  3. Save every mouse point from #2 in an array.
  4. When the user has finished defining their cutout region:

    • Clear the canvas.
    • Draw and fill the cutout area using the saved points in the arry.
    • Set context.globalCompositeOperation='source-in'. This mode will cause any new drawings to appear only where the newly drawn pixels and the existing pixels overlap and every thing else is made transparent. In common terms: New pixels will be "clipped" into the user defined cutout and new pixels will not appear outside the cutout.
    • Redraw the image.

The result is the second drawing of the image will appear only inside the user defined cutout. Everything else will be transparent.

Finally, you can use var url=canvasElement.toDataURL to save the cropped canvas image into a .png dataURL. If you then want an actual image from this dataURL you can var img=new Image() and set the img.src=url.

markE
  • 102,905
  • 11
  • 164
  • 176