William DA SILVA
Web Developer

Today I learned about data attribute in FabricJS

Written on: Jan 23, 2021 • Last update: Jan 23, 2021

Passing additional informations to any FabricJS object.

Today I learned that you can store any additional informations to your Fabric Objects through the data attribute. It's quite hidden in the documentation but as you search deeper you can see that there are two attributes that are there, not used by Fabric itself but just for convenience.

With that said, to add your custom informations to any of your Fabric Objects, you could pass a new object to the data value.

const object = new fabric.Rect({})

object.set('data', {
    first_item: 'Hello',
    second_item: 'World'

During the JSON export, these additional data can be found only if you allow them to be passed. By default, it's not included in the exported JSON.

// You can also includes "name" too, if you use it.
canvas.toJSON(['data', 'name'])

Then in your exported JSON, you'll see something like:

  "type": "rect",
  "version": "4.3.0",
  "originX": "left",
  "originY": "top",
  "left": 0,
  "top": 450,
  "width": 600,
  "height": 178,
  "fill": "#ffe6db",
  "stroke": null,
  "strokeWidth": 1,
  "strokeDashArray": null,
  "strokeLineCap": "butt",
  "strokeDashOffset": 0,
  "strokeLineJoin": "miter",
  "strokeMiterLimit": 4,
  "scaleX": 1,
  "scaleY": 1,
  "angle": 0,
  "flipX": false,
  "flipY": false,
  "opacity": 1,
  "shadow": null,
  "visible": true,
  "backgroundColor": "",
  "fillRule": "nonzero",
  "paintFirst": "fill",
  "globalCompositeOperation": "source-over",
  "skewX": 0,
  "skewY": 0,
  "rx": 0,
  "ry": 0,
  "data": {
    "first_item": "Hello",
    "second_item": "World"