开发基于fabric.js框架,我用一个group填充整个canvas,group第一个元素为一张图片,同样填充整个group(这里填充指设置大小一摸一样...),接着我设置这个canvas的isDrawingMode为true,让其可自由绘制,接着我希望用户画出来的轨迹,对应图片上区域的内容能被保存(类似抠图,但这里的框是由不规则的闭合曲线形成的)下来(svg,png,jpg,json什么的都好),接着我希望可以重绘这个区域。
下面是部分代码(vue开发)
1.导入后托管到vue
// main.js
import {fabric} from 'fabric'
Vue.prototype.$fb = fabric
// canvasmain.vue
// 生成canvas
this.c = new this.$fb.Canvas('canvas', {
width: CANVASWIDTH,
height: CANVASHEIGHT,
preserveObjectStacking: true,
fireRightClick: true,
this.isDrawingMode: true
})
// promise化Image的构造函数
formImg (src) {
return new Promise((resolve, reject) => {
this.$fb.Image.fromURL(src, function (img) {
resolve(img)
}, {
type: 'bkimg'
})
})
}
// 生成图片,并放入group中,最后放入canvas中
let img = await this.formImg(imgsrc)
this.group = new this.$fb.Group([img], {
type: 'group',
left: 0,
top: 0,
width: CANVASWIDTH,
height: CANVASHEIGHT,
lockScalingX: true,
lockScalingY: true
})
this.c.add(this.group)
// 保存闭合的曲线
this.c.on('mouse:up', function (e) {
if (this.c.isDrawingMode) {
let ps = this.c.freeDrawingBrush._points
// deviation是一个误差值
if (Math.abs(ps[0].x - ps[ps.length - 1].x) < this.deviation && Math.abs(ps[0].y - ps[ps.length - 1].y) < this.deviation) {
// 保存闭合的曲线(本地维护一个副本)
this.brushes.push(e.target)
}
}.bind(this))
我希望能将用户画中的区域对应图片的区域另存下来,可以是任何类型,求大神给与帮助