fabricjs - 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 对象添加到画布中?一旦我添加对象并添加其他对象,第一个对象就被删除了。如何逐个添加对象?
解决方案
您可以通过使用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>
推荐阅读
- python - 我想使用 PY visual 在 power bi 中应用 RFM 算法
- asp.net - 36未能在资源的“完整性”属性中找到有效的摘要“
' 具有计算的 SHA-256 完整性 ''。该资源已被阻止 - drools - OptaPlanner,DRL 错误,累积多头加倍
- azure - 在 Azure 上找不到资源组“$system”
- google-apps-script - 例外:您无权调用 insertRowsAfter(第 5 行)
- r - 将用户制作的函数应用于带有其他参数的向量
- reactjs - 我们如何将 Material-UI 中的所有 useStyles 放到一个文件中
- c++ - 带有空白的 std::vector
- google-cloud-platform - 通过 API 列出 Google Cloud 的项目特定区域
- git - 如何重命名拉取请求中使用的 git 分支 Github