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;
如何将json对象多次添加到画布中? 一旦我添加对象并添加其他对象,第一个对象就被删除了。如何逐个添加对象?
答案 0 :(得分:0)
您可以使用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);
})
});
&#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;