我想导出使用fabric.js创建的svg,所以我正在按照加载并保存
var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
var padding = 0;
fabric.Image.fromURL('http://netdna.webdesignerdepot.com/uploads/album_artwork/t2-7.jpg', function(img) {
img.scaleToWidth(100);
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.add(img);
var pattern = new fabric.Pattern({
source: function() {
patternSourceCanvas.setDimensions({
width: img.getWidth() + padding,
height: img.getHeight() + padding
});
return patternSourceCanvas.getElement();
},
repeat: 'repeat'
});
canvas.add(new fabric.Polygon([
{x: 185, y: 0},
{x: 250, y: 100},
{x: 385, y: 170},
{x: 0, y: 245} ], {
left: 0,
top: 200,
angle: -30,
fill: pattern
}));
$("#load").click(function(){
canvas.loadFromJSON(json, function() {
alert(' this is a callback. invoked when canvas is loaded! ');
});
});
});
$("#clear").click(function() {
// clear canvas
canvas.clear();
});
$("#remove_selected").click(function() {
// remove currently selected object
canvas.remove(canvas.getActiveObject());
});
$("#add_text").click(function(){
canvas.add(new fabric.Text('Hello Text!', {
fontFamily: 'Tahoma',
left: 400,
top: 225,
fontSize: 80,
textAlign: "left",
fill:"#FF0000" // Set text color to red
}));
});
$("#add_rect").click(function() {
// add red rectangle
canvas.add(new fabric.Rect({
width: 50,
height: 50,
left: 50,
top: 50,
fill: 'rgb(255,0,0)'
}));
});
$("#add_circle").click(function() {
// add green, half-transparent circle
canvas.add(new fabric.Circle({
radius: 40,
left: 50,
top: 50,
fill: 'rgb(0,255,0)',
opacity: 0.5
}));
});
$("#add_line").click(function() {
// add green, half-transparent circle
canvas.add(new fabric.Line({
radius: 40,
left: 50,
top: 50,
fill: 'rgb(0,255,0)',
opacity: 0.5
}));
});
var svgSrc = "image/upload/54b9ab31a3fb5.png";
$("#loadSVG").click(function(){
fabric.loadSVGFromURL(svgSrc, function (object) {
var group = new fabric.PathGroup(object, {
left: 165,
top: 100,
width: 295,
height: 211,
});
//set source path for svg
group.setSourcePath(svgSrc);
canvas.add(group);
canvas.renderAll();
});
});
$("#exportSVG").click(function(){
var json = JSON.stringify(canvas.toDatalessJSON());
$("body").append("
<div>
"+json+"
</di>
");
canvas.loadFromJSON(json, function() {
alert(' this is a callback. invoked when canvas is loaded! ');
});
});
$("#exporntSVG").click(function(){
group.fillColor = "#FF0000";
canvas.renderAll();
});
$("#save").click(function(){
});
但它对我不起作用,我可以看到导出的svg为JSON
,但我无法使用loadFromJSON
将其加载回svg并获得{{1}作为错误
示例小提琴:fiddle