JSON读写
上一节的操作过程有木有觉得太过繁琐?是的,我也觉得!所以我们有更方便的办法!
导入JSON
首先看一下下面这一段JSON:
javascript
const json = {
"model": [
{
"x": "0.00%",
"y": "0.00%",
"w": "100.00%",
"url": "/assets/cloth-w.png",
"type": "Image",
"name": "背景",
"reference": "stage"
}
],
"custom": [],
"view": {
"x": "0.00%",
"y": "0.00%",
"w": "100.00%",
"url": "/assets/rect.png",
"type": "Image",
"blendMode": "destination-in",
"reference": "stage"
}
}
- model:Array,代表模型图形的JSON
- custom:Array,代表素材的JSON
- view:object,代表DIY区域的图像对象
提示
导入上述JSON之前,请检查对应的图片链接资源是否存在。
我们可以直接通过Stage
对象的loadJson
,加载回显上面的JSON:
javascript
/* 监听json加载的事件 */
stage.on('loaded-json', (e) => {
console.log('json加载完毕!');
})
/* 导入JSON */
stage.loadJson(json, {
view: true, //指定是否加载DIY区域
model: true, //指定是否加载模型
custom: true, //指定是否加载素材
sync: false //指定是否同步等待所有素材加载完毕
});
/* 导入JSON,不操作舞台,返回一份舞台状态的快照数据,可通过alter方法替换当前舞台数据(参考撤销与恢复这一节) */
const snap = stage.loadJsonWithSnap(json, {
view: true, //指定是否加载DIY区域
model: true, //指定是否加载模型
custom: true, //指定是否加载素材
sync: false //指定是否同步等待所有素材加载完毕
});
导入单个图形
javascript
stage.load( {
"x": "25.00%",
"y": "10.00%",
"w": "50.00%",
"url": "/assets/pic.png",
"type": "Image",
"name": "素材",
"reference": "view"
})
导出JSON
javascript
/* 获取被激活的图形对象 */
const shape = stage.getActive();
/* 导出单个图形的JSON */
console.log(shape.toJson());
/* 导出整个舞台的JSON */
console.log(stage.toJson());
在线演示
你可以访问我们的演示案例来体验DIY.JS的功能。