我初始化画布并向其中添加图像。
this.canvas = new fabric.Canvas('c', {
hoverCursor: 'pointer',
selection: false,
allowTouchScrolling: false,
});
fabric.Image.fromURL(file_path, (img) => {
// After the image is uploaded, scaleRatio is calculated with Math.round(((img.height + img.width) / 2) * 0.05), capped at 80
// extendFabricLineToArrow function is called afterwards
});
extendFabricLineToArrow() {
let scaleR = this.scaleRatio;
try {
fabric.LineArrow = fabric.util.createClass(fabric.Line, {
type: 'lineArrow',
initialize: function (element, options) {
options || (options = {});
this.callSuper('initialize', element, options);
},
toObject: function () {
return fabric.util.object.extend(this.callSuper('toObject'));
},
_render: function (ctx) {
this.callSuper('_render', ctx);
if (this.width === 0 || this.height === 0 || !this.visible) return;
ctx.save();
let xDiff = this.x2 - this.x1;
let yDiff = this.y2 - this.y1;
let angle = Math.atan2(yDiff, xDiff);
ctx.translate((this.x2 - this.x1) / 2, (this.y2 - this.y1) / 2);
ctx.rotate(angle);
ctx.beginPath();
ctx.moveTo(Math.abs(scaleR), 0);
ctx.lineTo(-Math.abs(scaleR), Math.abs(scaleR));
ctx.lineTo(-Math.abs(scaleR), -Math.abs(scaleR));
ctx.closePath();
ctx.fillStyle = this.stroke;
ctx.fill();
ctx.restore();
}
});
fabric.LineArrow.fromObject = function (object, callback) {
callback && callback(new fabric.LineArrow([object.x1, object.y1, object.x2, object.y2], object));
};
fabric.LineArrow.async = true;
fabric.LineArrow.perPixelTargetFind = this.perPixelTargetFind;
fabric.LineArrow.targetFindTolerance = this.targetFindTolerance;
} catch (e) {
console.log('Error from extendFabric fct', e);
}
}
使用以下代码创建箭头:
fabric.LineArrow([x1, y1, x2, y2], { // with x2, y2 being the TIP of the arrow
strokeWidth: this.stroke_width,
fill: 'rgba(0,0,0,0)',
stroke: this.color,
padding: this.stroke_width
});
HammerJS用于压缩功能
hammer.on('pinch', (ev) => {
let point = new fabric.Point(ev.center.x, ev.center.y)
let delta = this.zoom * ev.scale;
this.canvas.zoomToPoint(point, delta);
this.canvas.renderAll();
});
在挤压过程中,箭头的尖端被应该是旧的对象边界所裁剪,从而导致对象变形。
可以在此链接https://share.vlinde.com/index.php/s/Rb29XbQMEfg4myP上找到视频示例
FabricJS版本:2.3.5 HammerJS v:2.0.8