Reputation: 1
I want to use pencil brush of fabric.js to make a tool to let user can draw an arc by dragging and dropping.
I make a function:
public static setArcBrush(canvas: fabric.Canvas, cellWidth: number) {
const ArcBrush = fabric.util.createClass(fabric.PencilBrush, {
type: 'ArcBrush',
width: cellWidth / 2,
initialize: function () {
this.callSuper('initialize', canvas);
},
onMouseDown: function (pointer: fabric.Point, options: fabric.IEvent<MouseEvent>) {
this.started = true;
this.startX = pointer.x;
this.startY = pointer.y;
this.endX = pointer.x;
this.endY = pointer.y;
this.arc = new fabric.Path('M 0 0', {
stroke: this.color,
strokeWidth: this.width,
fill: 'rgba(0,0,0,0)',
selectable: true,
objectCaching: false,
left: 0,
top: 0,
});
this.canvas.add(this.arc);
},
onMouseMove: function (pointer: fabric.Point, options: fabric.IEvent<MouseEvent>) {
if (!this.started) return;
this.endX = pointer.x;
this.endY = pointer.y;
const radius = Math.sqrt(Math.pow(this.endX - this.startX, 2) + Math.pow(this.endY - this.startY, 2)) / 2;
const centerX = (this.startX + this.endX) / 2;
const centerY = (this.startY + this.endY) / 2;
const startAngle = Math.atan2(this.startY - centerY, this.startX - centerX);
const endAngle = Math.atan2(this.endY - centerY, this.endX - centerX);
const largeArcFlag = endAngle - startAngle <= Math.PI ? "0" : "1";
const pathData = [
`M ${this.startX} ${this.startY}`,
`A ${radius} ${radius} 0 ${largeArcFlag} 1 ${this.endX} ${this.endY}`
].join(' ');
this.arc.set({ path: pathData });
this.canvas.renderAll();
},
onMouseUp: function (pointer: fabric.Point, options: fabric.IEvent<MouseEvent>) {
if (this.started) {
this.started = false;
this.arc.setCoords();
}
},
});
canvas.freeDrawingBrush = new ArcBrush();
canvas.isDrawingMode = true;
}
I use this function to draw an arc on a canvas, but the arc is invisible while I can use canvas.getObjects() to print the arc objects. I do not know why I can not see the arc.
Upvotes: 0
Views: 52