I want to crop image using fabricJs but I'm stuck on the calculus of the correct area to be cropped.
When I click on the crop button, it doesn't crop the image to the correct area.
The calculation is wrong.
Here's my crop code:
function centerXY (w, h) {
return {
x: canvas.width / 2 - w / 2,
y: canvas.height / 2 - h / 2
}
}
// zoneWidth: width of area where I want to cropped
// zoneHeight: height of area where I want to cropped
$('#crop').click(function () {
var zoom = canvas.getZoom()
const imgTop = canvasImage.top
const imgLeft = canvasImage.left
const {x, y} = centerXY(zoneWidth, zoneHeight)
let top = zoneHeight - imgTop - y
let left = zoneWidth - imgLeft - x
zoneWidth /= zoom
zoneHeight /= zoom
canvasImage.clipTo = ctx => {
ctx.rect(left, top, zoneWidth, zoneHeight)
};
canvas.renderAll()
})
This calculation is based on this post: Crop Functionality using FabricJs
Here's the demo.
Note: You can use the input type range to zoom out and see where the image is cropped.
I solved my problem. Here's the solution:
$('#crop').click(function () {
var zoom = canvas.getZoom()
let top = zoneY // Top position of area
let left = zoneX// Left position of area
zoneWidth /= zoom
zoneHeight /= zoom
canvas.clipPath = shapeRect; // fabric.Rect()
canvas.renderAll()
})
Instead of cropping the image, I cropped the canvas itself. And Using the position of the area to crop
Here the final demo: https://jsfiddle.net/58nvte7h/43/