Fabricjs实现裁剪功能

621 阅读1分钟

以下内容是使用fabricjs实现一个简单的裁剪功能案例

在html中添加一个canvas标签

<canvas width="800" height="800" id="canvas" style="border: 1px solid #ccc;"></canvas>

new一个fabricjs对象

const canvas = new fabric.Canvas('canvas')

添加一张图片

let beCropImage = null
 new fabric.Image.fromURL('./R.jpg', function (img) {
      beCropImage = img
      img.setControlsVisibility({
        mtr: false,
      })
      canvas.add(img)
    })

添加裁剪框

 // 添加裁剪宽
    let cropRect = null
    const addCropFn = () => {
      cropRect = new fabric.Rect({
        id: 'cropRect',
        left: 150,
        top: 150,
        stroke: 'red', // 设置边框颜色
        strokeWidth: 0.1, // 设置边框宽度
        width: 150,
        height: 150,
        opacity: 0.5,
        cornerColor: 'red',
        borderColor: 'red',
      })
      beCropImage.set({ selectable: false, evented: false })
      cropRect.setControlsVisibility({
        mtr: false,
      })
      canvas.add(cropRect)
    }

完成裁剪

 // 完成裁剪
    const finishCropFn = () => {
      const width = cropRect.width * cropRect.scaleX / beCropImage.scaleX
      const height = cropRect.height * cropRect.scaleY / beCropImage.scaleY
      const cropX = (cropRect.left - beCropImage.left) / beCropImage.scaleX
      const cropY = (cropRect.top - beCropImage.top) / beCropImage.scaleY
      beCropImage.set({
        left: cropRect.left,
        top: cropRect.top,
        cropX,
        cropY,
        width,
        height,
        selectable: true,
        evented: true
      })
      canvas.remove(cropRect)
    }