[fabricJS] draw alternative line with custom class
by ksoncan34
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script>
<p>
<button type="button" id="add">Add</button>
<button type="button" id="clear">Clear</button>
<button type="button" id="toJson">toJSON</button>
<button type="button" id="fromJson">fromJSON</button>
</p>
<p id="mouse">0/0</p>
<canvas id="mainCanvas" width="400" height="300"></canvas>
<p>Angle: <span id="angle"></span></p>
<p>Length: <span id="length"></span></p>
<div id="json"></div>
CSS
canvas {
display: block;
border: 1px solid;
}
JavaScript
// --- INIT --- //
var objUUID = 0;
var canvas = new fabric.Canvas("mainCanvas");
// --- EXTENSIONS --- //
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
id: this.id,
referenceId: this.referenceId
});
};
})(fabric.Object.prototype.toObject);
fabric.Point.prototype.angleRelativeFrom = function (startpoint) {
return Math.atan2(this.y - startpoint.y, this.x - startpoint.x) * 180 / Math.PI;
};
fabric.StaticCanvas.prototype.getObjectById = function (id) {
var obj = undefined;
this.getObjects().some(function (o) {
if (o.hasOwnProperty("id")) {
if (o.id === id) {
obj = o;
return true;
}
}
return false;
});
return obj;
};
fabric.ConnectorLine = fabric.util.createClass(fabric.Line, {
type: "connectorLine",
initialize: function (x1, y1, x2, y2, options) {
options = options || {};
this.id = options.id || objUUID++;
this.callSuper('initialize', [x1, y1, x2, y2], fabric.util.object.extend({
stroke: 'green',
strokeWidth: 2,
originX: "center",
originY: "center",
selectable: true,
lockScalingX: true,
lockScalingY: true,
lockRotation: true,
hasBorders: false,
hasControls: false,
perPixelTargetFind: true
}, options));
}
});
fabric.ConnectorLine.fromObject = function (obj) {
return new fabric.ConnectorLine(obj.x1, obj.y1, obj.x2, obj.y2, obj);
};
fabric.ConnectorHandle = fabric.util.createClass(fabric.Rect, {
type: "connectorHandle",
initialize: function (left, top, options) {
options = options || {};
this.id = options.id || objUUID++;
this.test('Hello');
this.callSuper('initialize', fabric.util.object.extend({
left: left,
top: top,
width: 10,
height: 20,
originX: "center",
originY: "center",
selectable: true,
lockScalingX: true,
...