Fabric.js将多个JSON添加到画布

时间:2018-06-05 03:52:04

标签: fabricjs



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>
&#13;
&#13;
&#13;

如何将json对象多次添加到画布中? 一旦我添加对象并添加其他对象,第一个对象就被删除了。如何逐个添加对象?

1 个答案:

答案 0 :(得分:0)

您可以使用fabric.util.enlivenObjects来实现相同目标。

<强> 样本

&#13;
&#13;
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);
  })
});
&#13;
#c{
  border:1px solid #333;
}
&#13;
<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>
&#13;
&#13;
&#13;