Related
How can I remove limiter and edit __editingSetCrop method so that I can correctly mask a image in fabricjs? In my current implementation, dragging is not smooth.
When you try to drag close to the edges, it breaks and stops moving. Instead, it should keep dragging on the available space. When I rotate the image and double click it moves outside of the box. also it not smooth.
here is my example https://www.awesomescreenshot.com/video/14279604?key=ee3022f0335fd9aa82c66628e7085cb3
const drawTopRightIcon = (
ctx,
left,
top,
__styleOverride,
fabricObject
) => {
ctx.save()
ctx.translate(left, top)
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 3
ctx.shadowBlur = 2
ctx.shadowColor = 'black'
ctx.moveTo(0, 0)
ctx.lineTo(0.5, 12)
ctx.moveTo(0, 0)
ctx.lineTo(-12, 0)
ctx.strokeStyle = '#ffffff'
ctx.stroke()
ctx.restore()
}
const drawTopLeftIcon = (
ctx,
left,
top,
__styleOverride,
fabricObject
) => {
ctx.save()
ctx.translate(left, top)
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 3
ctx.shadowBlur = 2
ctx.shadowColor = 'black'
ctx.moveTo(0, 0)
ctx.lineTo(0.5, 12)
ctx.moveTo(0, 0)
ctx.lineTo(12, 0)
ctx.strokeStyle = '#ffffff'
ctx.stroke()
ctx.restore()
}
const drawBottomLeftIcon = (
ctx,
left,
top,
__styleOverride,
fabricObject
) => {
ctx.save()
ctx.translate(left, top)
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 3
ctx.shadowBlur = 2
ctx.shadowColor = 'black'
ctx.moveTo(0, 0)
ctx.lineTo(0, -12)
ctx.moveTo(0, 0)
ctx.lineTo(12, 0)
ctx.strokeStyle = '#ffffff'
ctx.stroke()
ctx.restore()
}
const drawBottomRightIcon = (
ctx,
left,
top,
__styleOverride,
fabricObject
) => {
ctx.save()
ctx.translate(left, top)
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 3
ctx.shadowBlur = 2
ctx.shadowColor = 'black'
ctx.moveTo(0, 0)
ctx.lineTo(0, -12)
ctx.moveTo(0, 0)
ctx.lineTo(-12, 0)
ctx.strokeStyle = '#ffffff'
ctx.stroke()
ctx.restore()
}
const drawVerticalLineIcon = (
ctx,
left,
top,
__styleOverride,
fabricObject
) => {
const size = 24
ctx.save()
ctx.translate(left, top)
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 3
ctx.shadowBlur = 2
ctx.shadowColor = 'black'
ctx.moveTo(-0.5, -size / 4)
ctx.lineTo(-0.5, -size / 4 + size / 2)
ctx.strokeStyle = '#ffffff'
ctx.stroke()
ctx.restore()
}
const drawHorizontalLineIcon = (
ctx,
left,
top,
__styleOverride,
fabricObject
) => {
const size = 24
ctx.save()
ctx.translate(left, top)
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.beginPath()
ctx.lineCap = 'round'
ctx.lineWidth = 3
ctx.shadowBlur = 2
ctx.shadowColor = 'black'
ctx.moveTo(-size / 4, -0.5)
ctx.lineTo(-size / 4 + size / 2, -0.5)
ctx.strokeStyle = '#ffffff'
ctx.stroke()
ctx.restore()
}
const controlPositionIcons = {
tl: drawTopLeftIcon,
t: drawHorizontalLineIcon,
tr: drawTopRightIcon,
r: drawVerticalLineIcon,
br: drawBottomRightIcon,
b: drawHorizontalLineIcon,
bl: drawBottomLeftIcon,
l: drawVerticalLineIcon
}
const ControlPositions = {
TOP_LEFT: 'tl',
TOP: 't',
TOP_RIGHT: 'tr',
RIGHT: 'r',
BOTTOM_RIGHT: 'br',
BOTTOM: 'b',
BOTTOM_LEFT: 'bl',
LEFT: 'l'
}
fabric.StaticImage = fabric.util.createClass(fabric.Image, {
type: 'StaticImage',
_editingMode: false,
__editingImage: null,
cornerLengthEditing: 5,
cornerStrokeColorEditing: 'black',
cornerSizeEditing: 2,
cropType: 'rectangle',
initialize: function (element, options) {
options || (options = {});
this.filters = [];
this.cacheKey = 'texture' + fabric.Object.__uid++;
this.registerEditingEvents();
this.callSuper('initialize', options);
this._initElement(element, options);
this.applyCrop();
},
getElement: function () {
return this._element || {};
},
applyCrop: function () {
if (this.clipPath instanceof fabric.Object) {
this.clipPath = null
}
if (this.cropType === 'circle') {
this.clipPath = new fabric.Ellipse({
rx: this.width / 2,
ry: this.height / 2,
left: -this.width / 2,
top: -this.height / 2,
});
}
if (this.cropType === 'triangle') {
this.clipPath = new fabric.Triangle({
width: this.width,
height: this.height,
left: -this.width / 2,
top: -this.height / 2,
});
}
return this
},
registerEditingEvents: function () {
this.on('mousedblclick', () => {
if (!this._editingMode) {
return this.enterEditingMode()
} else {
this.exitEditingMode()
}
})
this.on('deselected', () => {
this.exitEditingMode()
})
},
enterEditingMode: function () {
if (this.selectable && this.canvas) {
this._editingMode = true
this.__editingImage = fabric.util.object.clone(this)
this.__editingImage.clipPath = null
const element = this.__editingImage.getElement()
const { top = 0, left = 0, cropX = 0, cropY = 0, scaleX = 1, scaleY = 1 } = this.__editingImage
this.__editingImage.set({
top: top - cropY * scaleY,
left: left - cropX * scaleX,
height: element.height,
width: element.width,
cropX: 0,
cropY: 0,
opacity: 0.6,
selectable: true,
evented: false,
excludeFromExport: true
})
this.canvas.add(this.__editingImage)
this.controls = this.__editingControls()
this.canvas.requestRenderAll()
this.on('moving', this.__editingOnMoving)
}
},
exitEditingMode: function () {
if (this.selectable && this.canvas) {
this._editingMode = false
if (this.__editingImage) {
this.canvas.remove(this.__editingImage)
this.__editingImage = null
}
this.off('moving', this.__editingOnMoving)
this.controls = fabric.Object.prototype.controls
this.fire('exit:editing', { target: this })
this.canvas.requestRenderAll()
}
},
__editingControls: function () {
const controls = Object.values(ControlPositions)
return controls.map(this.__createEditingControl.bind(this))
},
__createEditingControl: function (position) {
const cursor = position
.replace('t', 's')
.replace('l', 'e')
.replace('b', 'n')
.replace('r', 'w')
return new fabric.Control({
cursorStyle: cursor + '-resize',
actionName: `edit_${this.type}`,
render: controlPositionIcons[position],
positionHandler: this.__editingControlPositionHandler.bind(this, position),
actionHandler: this.__editingActionHandlerWrapper(position)
})
},
__editingActionHandlerWrapper: function (position) {
return (_event, _transform, x, y) => {
//let localPosition = this.getLocalPointer(_event)
this.__editingSetCrop(position, x, y, true)
return true
}
},
__editingOnMoving: function (event) {
if (this._editingMode && event.pointer) {
this.set('dirty', true) // trigger cache refresh
this.__editingSetCrop(ControlPositions.TOP_LEFT, this.left, this.top)
}
},
__editingSetCrop: function (
position,
x,
y,
resize = false
) {
if (this.__editingImage) {
const { top = 0, left = 0, width = 0, height = 0, scaleX = 1, scaleY = 1 } = this.__editingImage
if (position.includes('t')) {
const maxTop = top + height * scaleY - (resize ? 0 : this.getScaledHeight())
const minTop = Math.min(y, maxTop, this.top + this.getScaledHeight())
this.top = Math.max(minTop, top)
const cropY = Math.min((Math.min(Math.max(y, top), this.top) - top) / scaleY, height)
if (resize) {
this.height = Math.max(0, Math.min(this.height + (this.cropY - cropY), height))
}
this.cropY = cropY
} else if (position.includes('b') && resize) {
const minHeight = Math.min((y - top) / scaleY - this.cropY, height - this.cropY)
this.height = Math.max(0, minHeight)
}
if (position.includes('l')) {
const maxLeft = left + width * scaleX - (resize ? 0 : this.getScaledWidth())
const minLeft = Math.min(x, maxLeft, this.left + this.getScaledWidth())
this.left = Math.max(minLeft, left)
const cropX = Math.min((Math.min(Math.max(x, left), this.left) - left) / scaleX, width)
if (resize) {
this.width = Math.max(0, Math.min(this.width + (this.cropX - cropX), width))
}
this.cropX = cropX
} else if (position.includes('r') && resize) {
const minWidth = Math.min((x - left) / scaleX - this.cropX, width - this.cropX)
this.width = Math.max(0, minWidth)
}
this.applyCrop()
}
},
__editingControlPositionHandler: function (position) {
const xMultiplier = position.includes('l') ? -1 : position.length > 1 || position === 'r' ? 1 : 0
const yMultiplier = position.includes('t') ? -1 : position.length > 1 || position === 'b' ? 1 : 0
const x = (this.width / 2) * xMultiplier
const y = (this.height / 2) * yMultiplier
return fabric.util.transformPoint(
new fabric.Point(x, y),
fabric.util.multiplyTransformMatrices(this.canvas.viewportTransform, this.calcTransformMatrix())
)
},
__renderEditingControl: function (
position,
ctx,
left,
top
) {
ctx.save()
ctx.strokeStyle = this.cornerStrokeColorEditing
ctx.lineWidth = this.cornerSizeEditing
ctx.translate(left, top)
if (this.angle) {
ctx.rotate(fabric.util.degreesToRadians(this.angle))
}
ctx.beginPath()
const x = position.includes('l') ? -ctx.lineWidth : position.includes('r') ? ctx.lineWidth : 0
const y = position.includes('t') ? -ctx.lineWidth : position.includes('b') ? ctx.lineWidth : 0
if (position === 'b' || position === 't') {
ctx.moveTo(x - this.cornerLengthEditing / 2, y)
ctx.lineTo(x + this.cornerLengthEditing, y)
} else if (position === 'r' || position === 'l') {
ctx.moveTo(x, y - this.cornerLengthEditing / 2)
ctx.lineTo(x, y + this.cornerLengthEditing)
} else {
if (position.includes('b')) {
ctx.moveTo(x, y - this.cornerLengthEditing)
} else if (position.includes('t')) {
ctx.moveTo(x, y + this.cornerLengthEditing)
}
ctx.lineTo(x, y)
if (position.includes('r')) {
ctx.lineTo(x - this.cornerLengthEditing, y)
} else if (position.includes('l')) {
ctx.lineTo(x + this.cornerLengthEditing, y)
}
}
ctx.stroke()
ctx.restore()
},
});
fabric.StaticImage.fromURL = function (url, callback, imgOptions) {
fabric.util.loadImage(url, function (img, isError) {
callback && callback(new fabric.StaticImage(img, imgOptions), isError);
}, null, imgOptions && imgOptions.crossOrigin);
};
fabric.StaticImage.fromObject = function (options, callback) {
fabric.util.loadImage(
options.src,
function (img) {
return callback && callback(new fabric.StaticImage(img, options))
},
null,
{ crossOrigin: 'anonymous' }
)
}
tried various fabric js libraries
I am trying to subclass a fabricjs Image for a barcode field.
import {fabric} from 'fabric';
import bwipjs from 'bwip-js';
class Barcode extends fabric.Image {
constructor(options) {
console.log("constructor", options);
var wrkOptions = {
width: options.position.width,
height: options.position.height,
left: options.position.left,
top: options.position.top,
angle: options.direction || 0,
form: options.form || {}
};
super(wrkOptions);
this.type = 'barcode';
let canvas1 = document.createElement('canvas');
canvas1.width = options.position.width;
canvas1.height = options.position.height;
var bcOptions = { bcid: 'code128', // Barcode type
text: '0123456789', // Text to encode
scale: 3, // 3x scaling factor
height: 10, // Bar height, in millimeters
includetext: true, // Show human-readable text
textxalign: 'center', // Always good to set this
};
bwipjs.toCanvas(canvas1, bcOptions);
var dataUrl = canvas1.toDataURL("image/png");
this.setSrc(dataUrl, () => {
if (!options.restore) {
curCanvas.add(this);
this.setOptions(options);
this.setCoords();
}
},
wrkOptions);
}
toObject = () =>{
var ret = {
type: this.type,
position: {top: this.top, left: this.left, width: this.width * this.scaleX, height: this.height * this.scaleY},
color: this.fill,
direction: this.angle,
form: this.form
};
console.log(ret);
return ret;
}
}
fabric.Barcode = Barcode;
fabric.Barcode.fromObject = function (options, callback) {
var wrkOptions = {restore: true, ...options};
var bc = new Barcode(wrkOptions);
callback(bc);
};
Creating the barcode field works:
onAddBarcode = () => {
var color = Math.floor(Math.random() * 256 * 256 *256).toString(16);
var options = {
color: "#" + color,
position: {
top: Math.floor(Math.random() * 500),
left: Math.floor(Math.random() * 500),
width: Math.floor(Math.random() * 100),
height: Math.floor(Math.random() * 100)
}
};
return ret;
...this.getRandom()
};
var barcode = new Barcode(options);
}
But serializing and restoring the canvas does not work:
onReload = () => {
var json = JSON.stringify(this.canvas, null, 2);
this.canvas.clear();
this.canvas.loadFromJSON(json, this.canvas.renderAll.bind(this.canvas));
}
It does restore a barcode image, but it is positioned wrongly outside of the controls.
What's wrong?
I got it positioned correctly (after restoring) by resetting the position attributes in the setSrc callback:
....
this.setSrv(dataUrl,
() => {
this.left = options.position.left;
this.top = options.position.top;
this.angle = options.direction || 0;
this.width = options.position.width;
this.height = options.position.height;
this.setCoords();
callback(this);
});
Fabric.js 2.3.6
I'm trying to clip an object to a path drawn with the free drawing bush. The code fails to show the image inside the path and I'm not sure what I'm doing wrong.
Multiple objects could be clipped, so I can't apply the path to the canvas itself.
let image = new Image();
let object;
let canvas;
// canvas
canvas = new fabric.Canvas("canvas", {
backgroundColor: "lightgray",
width: 1280,
height: 720,
preserveObjectStacking: true,
selection: false
});
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.color = "black";
canvas.freeDrawingBrush.width = 2;
canvas.on("path:created", function(options) {
clip(options.path);
});
// clip
function clip(path) {
object.set({
clipTo: function(ctx) {
path.render(ctx);
}
});
canvas.requestRenderAll();
}
// image
image.onload = function() {
object = new fabric.Image(image, {
width: 500,
height: 500,
top: 50,
left: 50
});
canvas.add(object);
};
image.src = "http://i.imgur.com/8rmMZI3.jpg";
https://jsfiddle.net/o91rv38q/7/
In order to clip on the same spot when is path has been drawn, you need to reset pathOffset for a SVG path, and setTransform to the ctx. Your clip function will look like:
function clip(path) {
path.set({pathOffset: {x: 0, y: 0}});
object.set({
clipTo: function(ctx) {
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.beginPath();
path._renderPathCommands(ctx);
ctx.restore();
}
});
canvas.requestRenderAll();
}
_renderPathCommands - renders a path.
Updated fiddle
To clip multiple objects you'll need to have some sort of an array of objects and then combine then into single path:
function combinePaths (paths) {
if (!paths.length) {
return null;
}
let singlePath = paths[0].path;
for (let i = 1; i < paths.length; i++){
singlePath = [...singlePath, ...paths[i].path];
}
return new fabric.Path(singlePath, {
top: 0,
left: 0,
pathOffset: {
x: 0,
y: 0
}
});
}
Here is an example with multiple paths to clip:
// canvas
let canvas = new fabric.Canvas("canvas", {
backgroundColor: "lightgray",
width: 1280,
height: 720,
preserveObjectStacking: true,
selection: false
});
let paths = [];
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.color = "black";
canvas.freeDrawingBrush.width = 2;
canvas.on("path:created", function (options) {
paths.push(options.path);
clip(combinePaths(paths));
});
function combinePaths(paths) {
if (!paths.length) {
return null;
}
let singlePath = paths[0].path;
for (let i = 1; i < paths.length; i++) {
singlePath = [...singlePath, ...paths[i].path];
}
return new fabric.Path(singlePath, {
top: 0,
left: 0,
pathOffset: {
x: 0,
y: 0
}
});
}
function clip(path) {
if (!path) {
return;
}
object.set({
clipTo: function (ctx) {
var retina = this.canvas.getRetinaScaling();
ctx.save();
ctx.setTransform(retina, 0, 0, retina, 0, 0);
ctx.beginPath();
path._renderPathCommands(ctx);
ctx.restore();
}
});
canvas.requestRenderAll();
}
// image
let image = new Image();
let object;
image.onload = function () {
object = new fabric.Image(image, {
width: 500,
height: 500,
top: 50,
left: 50
});
object.globalCompositeOperation = 'source-atop';
canvas.add(object);
};
image.src = "http://i.imgur.com/8rmMZI3.jpg";
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.6/fabric.js"></script>
<canvas id="canvas" width="1280" height="720"></canvas>
I have a canvas and have 2 images on it one is not evented and other we can change. Now I'm trying to change/replace image using file input, everything is fine just while changing the image it replaces the one I want but also adds one on top. I want to change the Image with id='changeimg'
//Add Image to Canvas
var imgObj = new Image();
//imgObj.id='changeimg';
imgObj.src = "blank.png";
var imgmain = imgObj.onload = function() {
var image = new fabric.Image(imgObj);
image.set({
id: 'changeimg',
angle: 0,
height: 350,
width: canvas.getWidth(),
align: 'mid', //added
originX: 'center', //added
originY: 'center', //added
});
canvas.centerObject(image);
canvas.add(image);
}
var imgObj1 = new Image();
//imgObj1.id='backgroundimg';
imgObj1.src = "template1.png";
var imgmain = imgObj1.onload = function() {
var image1 = new fabric.Image(imgObj1);
image1.set({
id: 'backgroundimg',
angle: 0,
height: canvas.getHeight(),
width: canvas.getWidth(),
evented: false,
});
//canvas.centerObject(image1);
canvas.add(image1);
}
//On Image Browse and Set on Canvas
document.getElementById('uploadedImg').onchange = function handleImage(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(file) {
addImage(file.target.result);
}
reader.readAsDataURL(file);
}
function addImage(imgLink) {
fabric.Image.fromURL(imgLink, function(img) {
img.set({
'left': 50
});
img.set({
'top': 150
});
img.scaleToWidth(250);
img.scaleToHeight(250);
var cnt = 0;
var objs = canvas.getObjects();
//var objs = canvas.getActiveObject();
if (objs.length > 0) {
objs.forEach(function(e) {
if (e && e.type === 'image' && e.id === "changeimg") {
e._element.src = imgLink;;
canvas.renderAll();
cnt = 1;
}
});
}
});
}
Use imageEl.setSrc to change source of image element.
DEMO
var canvas = new fabric.Canvas('c');
fabric.Image.fromURL("https://picsum.photos/200/300/?random", function(img) {
img.set({
id: 'changeimg',
align: 'mid', //added
originX: 'center', //added
originY: 'center', //added,
scaleX: 200 / img.width,
scaleY: 200 / img.height,
});
canvas.centerObject(img);
canvas.add(img);
image = img;
})
fabric.Image.fromURL("https://picsum.photos/200/250/?random", function(img) {
img.set({
id: 'backgroundimg',
angle: 0,
scaleX: canvas.width / img.width,
scaleY: canvas.height / img.height,
});
//canvas.centerObject(image1);
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
})
//On Image Browse and Set on Canvas
document.getElementById('uploadedImg').onchange = function handleImage(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(file) {
addImage(file.target.result);
}
reader.readAsDataURL(file);
}
function addImage(imgLink) {
fabric.Image.fromURL(imgLink, function(img) {
var objects = canvas.getObjects();
for (var i = 0, l = objects.length; i < l; i++) {
if (objects[i].id == 'changeimg') {
imageEl = objects[i];
break
}
}
if (imageEl) {
imageEl.setSrc(img.getSrc(), function() {
canvas.renderAll()
imageEl.setCoords();
},{
left: 50,
top: 150,
scaleX: 150 / img.width,
scaleY: 200 / img.height,
})
}
});
}
canvas{
border:2px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.4/fabric.js"></script>
<canvas id="c" width=500 height=500></canvas><br>
<input type='file' id='uploadedImg'>
fabricJS Version 2.2.3
Test jsFiddle
I'm trying to use LabeledRect subclass but my problem is that whenever I try to load it from JSON, it does not render, and I got no error in console. See the fiddle below.
How can I render it properly ? I think my problem is in the fromObject func but I got no idea where.
/**
* fabric.js template for bug reports
*
* Please update the name of the jsfiddle (see Fiddle Options).
* This templates uses latest dev verison of fabric.js (https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js).
*/
// initialize fabric canvas and assign to global windows object for debug
var canvas = window._canvas = new fabric.Canvas('c');
// ADD YOUR CODE HERE
var json = '{"version":"2.2.3","objects":[{"type":"labeledRect","version":"2.2.3","originX":"left","originY":"top","left":0,"top":0,"width":100,"height":50,"fill":"#faa","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"rx":0,"ry":0,"label":"1"}]}';
fabric.LabeledRect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
initialize: function(options) {
options || (options = {});
this.callSuper('initialize', options);
this.set('label', options.label || '');
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label')
});
},
_render: function(ctx) {
this.callSuper('_render', ctx);
ctx.font = '20px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width / 2, -this.height / 2 + 20);
}
});
fabric.LabeledRect.fromObject = function(object, callback) {
fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
delete object.objects;
callback && callback(new fabric.LabeledRect(enlivenedObjects, object));
});
};
fabric.LabeledRect.async = true;
canvas.loadFromJSON(json);
canvas.renderAll();
canvas {
border: 1px solid #999;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="1000" height="600"></canvas>
fabric.LabeledRect.fromObject = function(object, callback) {
return fabric.Object._fromObject('LabeledRect', object, callback);
};
call fabric.Object._fromObject inside fromObject
DEMO
var canvas = window._canvas = new fabric.Canvas('c');
var json = '{"version":"2.2.3","objects":[{"type":"labeledRect","version":"2.2.3","originX":"left","originY":"top","left":0,"top":0,"width":100,"height":50,"fill":"#faa","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"rx":0,"ry":0,"label":"1"}]}';
fabric.LabeledRect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
initialize: function(options) {
options || (options = {});
this.callSuper('initialize', options);
this.set('label', options.label || '');
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label')
});
},
_render: function(ctx) {
this.callSuper('_render', ctx);
ctx.font = '20px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width / 2, -this.height / 2 + 20);
}
});
fabric.LabeledRect.fromObject = function(object, callback) {
return fabric.Object._fromObject('LabeledRect', object, callback);
};
canvas.loadFromJSON(json,canvas.renderAll.bind(canvas));
canvas {
border: 1px solid #999;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="1000" height="600"></canvas>