Here's a quick tour showing how to crop & save a user-dragged cutout of an image:
- Draw the image on the canvas.
- 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.
- Save every mouse point from #2 in an array.
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
.