user3655824
user3655824

Reputation: 27

Fabric.js Add multiple JSON to canvas

var canvas = new fabric.Canvas('c', {
  selection: false
});
var txt1 = {
  objects: [{
    type: "text",
    originX: "center",
    originY: "center",
    left: 100,
    top: 60,
    width: 200,
    height: 30,
    fill: "rgb(0,0,0)",
    shadow: null,
    visible: true,
    text: "Test Text 01",
    fontSize: 30,
    fontWeight: "normal",
    fontFamily: "Arial",
  }]
};
var txt2 = {
  objects: [{
    type: "text",
    originX: "center",
    originY: "center",
    left: 200,
    top: 100,
    width: 200,
    height: 30,
    fill: "rgb(0,0,0)",
    shadow: null,
    visible: true,
    text: "Test Text 02",
    fontSize: 30,
    fontWeight: "normal",
    fontFamily: "Arial",
  }]
};

$('#t1').on('click', function(e) {
  canvas.loadFromDatalessJSON(txt1);
});

$('#t2').on('click', function(e) {
  canvas.loadFromDatalessJSON(txt2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.1/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button id="t1">add text 01</button>
<button id="t2">add text 02</button>

<canvas id="c" width="600" height="300"></canvas>

How can I add json object in to canvas several time? Once I add object and add other object, first object was removed. How can I add object one by one?

Upvotes: 0

Views: 1363

Answers (1)

Durga
Durga

Reputation: 15604

You can achieve the same by using fabric.util.enlivenObjects.

DEMO

var canvas = new fabric.Canvas('c', {
  selection: false
});

var txt1 = {
  objects: [{
    type: "text",
    originX: "center",
    originY: "center",
    left: 100,
    top: 60,
    width: 200,
    height: 30,
    fill: "rgb(0,0,0)",
    shadow: null,
    visible: true,
    text: "Test Text 01",
    fontSize: 30,
    fontWeight: "normal",
    fontFamily: "Arial",
  }]
};
var txt2 = {
  objects: [{
    type: "text",
    originX: "center",
    originY: "center",
    left: 200,
    top: 100,
    width: 200,
    height: 30,
    fill: "rgb(0,0,0)",
    shadow: null,
    visible: true,
    text: "Test Text 02",
    fontSize: 30,
    fontWeight: "normal",
    fontFamily: "Arial",
  }]
};

$('#t1').on('click', function(e) {
  fabric.util.enlivenObjects(txt1.objects, function(objects) {
    canvas.add(...objects);
  })
});


$('#t2').on('click', function(e) {
  fabric.util.enlivenObjects(txt2.objects, function(objects) {
    canvas.add(...objects);
  })
});
#c{
  border:1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button id="t1">add text 01</button>
<button id="t2">add text 02</button>

<canvas id="c" width="600" height="300"></canvas>

Upvotes: 1

Related Questions