序列化与反序列化

fabric 的神奇之处在于可以将画布进行序列化和反序列化,已达到重用的目的

序列化

通过 canvas.toJSON() 将画布进行序列化:

var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
  width: 100,
  height: 100,
  fill: 'red'
});
canvas.add(rect);
console.log(JSON.stringify(canvas.toJSON()));

反序列化

通过 canvas.loadFromJSON 加载已经被序列化的JSON字串:

var canvas = new fabric.Canvas('canvas');
canvas.loadFromJSON('{"objects":[{"type":"rect","left":50,"top":50,"width":20,"height":20,"fill":"green","overlayFill":null}')

SVG

var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
  width: 100,
  height: 100,
  fill: 'red'
});
canvas.add(rect);
console.log(canvas.toSVG());

返回:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1000" height="1000" viewBox="0 0 1000 1000" xml:space="preserve">
<desc>Created with Fabric.js 3.3.0</desc>
<defs>
</defs>
<g transform="matrix(1 0 0 1 50.5 50.5)"  >
<rect style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(255,0,0); fill-rule: nonzero; opacity: 1;"  x="-50" y="-50" rx="0" ry="0" width="100" height="100" />
</g>
</svg>

将之另存为 svg 文件即可很容易地进行复用

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress