计算要裁剪的正确区域 fabricjs

Calculate the correct area to be cropped fabricjs

我想使用 fabricJs 裁剪图像,但我卡在要裁剪的正确区域的微积分上。

当我点击裁剪按钮时,它没有将图像裁剪到正确的区域。

计算错误

这是我的裁剪代码:

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()
  })

这个计算是基于这个post:Crop Functionality using FabricJs

这是demo.

注意:您可以使用输入类型范围缩小并查看裁剪图像的位置。

我解决了我的问题。 这是解决方案:

 $('#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()
  })

我没有裁剪图像,而是裁剪了 canvas 本身。 并使用区域的位置进行裁剪

最后的演示:https://jsfiddle.net/58nvte7h/43/