计算正确的裁剪区域

时间:2019-01-18 07:49:14

标签: javascript math fabricjs calculation

我想使用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()
  })

此计算基于以下信息:enter image description here

这里是Crop Functionality using FabricJs

注意:您可以使用输入类型范围进行缩小并查看在哪里裁剪图像。

请帮忙!!

非常感谢。

此致

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。 解决方法如下:

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

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

这是最终的演示:https://jsfiddle.net/58nvte7h/43/