以下内容是使用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)
}