RaphaelJS到SVG来

时间:2011-06-15 06:35:20

标签: javascript canvas svg png raphael

我试图让用户下载SVG图片为PNG。 您可以通过JSFIDDLE

访问代码

SVG到CANVAS部分无效。

已经添加了canvg和Mozillas的代码,他们都没有工作。还添加了Canvas2Image,如果canvas具有元素,它应该有效。

2 个答案:

答案 0 :(得分:4)

感谢gabelerner开发的canvg帮助我解决了这个问题

  1. 基于Problem saving as png a SVG generated by Raphael JS in a canvas,删除svg
  2. 中标记之间的所有空格
  3. 基于Problem saving as png a SVG generated by Raphael JS in a canvas图片的href更改为xlink:href
  4. 基于gabelerner,将xmlns:xlink =“http://www.w3.org/1999/xlink”添加到svg xlmns
  5. 基于gabelerner,图片必须在同一个域下 - 没有crossside
  6. 基于gabelerner,Canvas2Image无法在框架内工作,这意味着没有FIDDLE(因此我删除了FIDDLE部分以使其清晰)
  7. 以下是您可能想要的示例SVG和JS部分

    var svg_XML_NoSpace = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1024" height="768"><desc>Created with Raphaël</desc><defs></defs><image x="0" y="0" width="1024" height="768" preserveaspectratio="none" xlink:href="http://<mydomain>/<myfolder>/<myfile>"></image><path fill="none" stroke="#ff0000" d="M414,114L722,114" style="stroke-width: 3px;" stroke-width="3"></path></svg>'; //based on gabelerner
    
    //add canvas into body        
    var canvasID = "myCanvas";
    var canvas = document.createElement('canvas');
    canvas.id = canvasID;
    document.body.appendChild(canvas);
    
    //convert svg to canvas
    canvg(document.getElementById(canvasID), svg_XML_NoSpace, { 
        ignoreMouse: true, ignoreAnimation: true, 
        renderCallback: function () {
             //save canvas as image
             Canvas2Image.saveAsPNG(document.getElementById(canvasID));  
             }
    } );
    

答案 1 :(得分:0)

尝试使用fabric.js将SVG转换为画布(此处为demo,当您单击侧边栏中的按钮时,svg将实时转换为画布)。

Fabric不支持所有SVG功能,但它适用于简单的情况。

以下是使用loadSVGFromURL

的示例

1)你需要&lt; canvas&gt;元素:

<canvas id="my-canvas"></canvas>

2)从画布中初始化fabric.Element

var canvas = new fabric.Element('my-canvas');

3)通过XHR获取SVG:

canvas.loadSVGFromURL('path_to_your_shape.svg', function(objects, options) {

  // `objects` is now an array of fabric objects representing 
  // svg shapes from the document
  // if it's one shape, we'll just work with that
  // if it's more than one — we'll create a unified group out of it, 
  // using `fabric.PathGroup`

  var loadedObject = objects.length > 1 
    ? new fabric.PathGroup(objects, options) 
    : objects[0];

  // we can now change object's properties like left, top, angle, opacity, etc.
  // this is not necessary, of course

  loadedObject.set({
    left: 123,
    top: 321,
    angle: 55,
    opacity: 0.3
  });

  // and add it to canvas

  canvas.add(loadedObject);
});
相关问题