首页 > 解决方案 > Fabric.js 将多个 JSON 添加到画布

问题描述

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>

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

标签: fabricjs

解决方案


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

演示

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>


推荐阅读