I'm working with fabricJS. It's an awesome library for drawing.
var data = JSON.stringify(canvas);
Above command is used to get all the objects along with their properties in JSON
format. However, I want to stringfy only an object.
For eg. Creating a rectangle using fabric
var rec = new fabric.Rect({
left: mouse_pos.x,
top: mouse_pos.y,
width: 75,
height: 50,
fill: 'white',
stroke: 'black',
strokeWidth: 3,
padding: 10
});
canvas.add(rec);
I want to get the JSON
of only this object(rectangle) being added to the canvas and not the JSON
of whole of the canvas being rendered. May be something like var data = JSON.stringfy(rec);
. Is there any way to do so because I want to send the latest object being added to the canvas over sockets and not the whole canvas object which will in turn consumes unnecessary bandwidth because of the JSON object size.
Yes you can! :)
var rect = new fabric.Rect({
left: mouse_pos.x,
top: mouse_pos.y,
width: 75,
height: 50,
fill: 'white',
stroke: 'black',
strokeWidth: 3,
padding: 10
});
canvas.add(rect);
// get last item
var obj = canvas.item(canvas.size() - 1);
// stringify only one object
var json = JSON.stringify(obj);
Can't you just turn your options object into JSON? Then you could send it through sockets, get the JSON on your receiver, parse it and apply into the fabric.Rect
function to draw your rect there.
var options = {
left: mouse_pos.x,
top: mouse_pos.y,
width: 75,
height: 50,
fill: 'white',
stroke: 'black',
strokeWidth: 3,
padding: 10
};
var rec = new fabric.Rect(options);
canvas.add(rec);
var yourData = JSON.stringify(options); // turns your options object into JSON
// ...rest of your code, that sends it through sockets...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.