How to implement crop tool on the image that is loaded on the canvas using fabric.js ? I have a image loaded on the canvas .Now i want to implement crop tool where the user is allowed to crop the image and reload it on to the canvas when he is done.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
(This answer is an iteration on the fiddle in Tom's answer. Thank you, Tom, for getting me down the road.)
You can crop in Fabric.js using either fabric.Object.clipTo() or fabric.Object.toDataURL(). The
clipTo()
method retains the original image and displays a crop via a mask. ThetoDataURL()
method creates a new image.My full example uses the
clipTo()
method. I have included a small chunk of code at the end showing thetoDataURL()
method.Solution 1
Summary
Difference's from Tom's answer
In the fiddle in Tom's answer, there are a couple of minor things I wanted to change. So in my example the differences are
The crop box work from left to right and right to left (Tom's works from right to left only)
You have more than one chance to draw the crop box (attempting to re-draw the crop box in Tom's causes box to jump)
Works with Fabric.js v1.5.0
Less code.
The Code
Solution 2
Or, instead of using
clipTo()
like above, we could generate a new image usingtoDataURL()
. Something like thisIn Summary
el.selectable = false
Sorry, let me explain. The
ctx.rect
will crop the image from the center point of the object. Also thescaleX
factor should be taken into account.Complete example: http://jsfiddle.net/hellomaya/kNEaX/1/
And check out this http://jsfiddle.net/hellomaya/hzqrM/ for generating the select box. And a reference for the Fabric events: https://github.com/kangax/fabric.js/wiki/Working-with-events