在Fabric.js中导入SVG无法正常工作

时间:2013-04-24 07:07:29

标签: fabricjs

我正在创建SVG形状并将其导出到数据库。 jsfiddle就是这里 - http://jsfiddle.net/rafi_ccj/MASeK/1/

代码如下。

HTML部分:

<button id="make_svg">toSVG</button>
<div id="canvas-wrapper">
    <canvas id="canvas" width="400px" height="200px"></canvas>
</div>

Javascript部分:

var canvas = new fabric.Canvas('canvas');


canvas.add(new fabric.Rect({
    left: 100,
    top: 100,
    angle: 0,
    fill: 'rgba(23,23,125,0.5)',
    strokeWidth: 0.1,
    stroke: '#FF0000',
    width: 200,
    height: 200,
    opacity: 1
}));
canvas.add(new fabric.Circle({
    left: 100,
    top: 100,
    fill: 'rgba(45, 255, 34, 0.5)',
    strokeWidth: 0.1,
    stroke: '#FF0000',
    radius: 100,
    opacity: 1
}));

$("#make_svg").click(function () {
    canvas_data = canvas.toSVG();
    console.log(canvas_data);
});

然后我将svg导入到画布中,但它与我创建的不一样。 jsfiddle在这里 - http://jsfiddle.net/rafi_ccj/2vtz2/

,代码在--- ---

html部分

<div id="canvas-wrapper">
    <canvas id="canvas" width="900px" height="800px"></canvas>
</div>

javascript部分在这里 -

var canvas = new fabric.Canvas('canvas');

var canvas_data = '<?xml version="1.0" 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="400" height="200" xml:space="preserve"><desc>Created with Fabric.js 1.1.8</desc><defs></defs><rect x="-100" y="-100" rx="0" ry="0" width="200" height="200" style="stroke: #FF0000; stroke-width: 0.1; stroke-dasharray: ; fill: rgba(23,23,125,0.5); opacity: 1;" transform="translate(100 100)"/><circle cx="0" cy="0" r="100" style="stroke: #FF0000; stroke-width: 0.1; stroke-dasharray: ; fill: rgba(45, 255, 34, 0.5); opacity: 1;" transform="translate(100 100)"/></svg> ';

fabric.loadSVGFromString(canvas_data, function (objects, options) {
    var loadedObject = fabric.util.groupSVGElements(objects, options);

    loadedObject.set({
        left: 400,
        top: 200
    });
    loadedObject.setCoords();
    canvas.add(loadedObject);
    canvas.calcOffset();
});

我也注意到,如果我使用三角形,导入后它不存在,它就会消失。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

我已经通过使所有对象成为一个组元素来解决这个问题,并且在创建具有这些对象的组之后,我已经在设备中使用svg扩展名保存了它,并且在数据库中也保存了json格式。代码如下 -

var group = new fabric.Group([],{
      left: 200,
      top: 200
 });

 var canvas_item = canvas.item(0), x = 0;
 while (canvas_item != undefined) {
      group.addWithUpdate(canvas_item);
      x += 1;
      canvas_item = canvas.item(x);
 }
 canvas.clear();
 canvas.add(group);
 //then use canvas.toDatalessJSON(); and save it to database. while importing this data //use following codes

 var canvas_data = JSON.stringify(canvas.toDatalessJSON());

 canvasJSONdata = JSON.stringify(canvas.toDatalessJSON());
 var stringifiedCanvasJSONdata = JSON.parse(canvasJSONdata,'');
 var base_64 = canvas.toDataURL('png');

现在它完美无缺!虽然我遇到了很多问题,但我学到了很多东西,我很享受!希望这个解决方案能在某一天帮助某人。