2012-06-02 69 views
9

我有一个带有jpg图像的网页,用户在使用Raphael的基础上绘制SVG涂鸦。如何将一个<image>元素添加到SVG DOM

我想允许用户保存的这个合并光栅化版本,他们这样做(我会做别的事情与SVG版本我自己)

当用户点击保存我想补充一点背景图像时以生成的SVG DOM作为元素,然后使用canvg将SVG写入画布元素。最后,我使用toDataUrl()方法将其转换为jpg。

我无法让中间的位工作 - 将图像添加到DOM的最佳方式是什么?当我使用下面的代码时,我得到一个说明appendChild()不是函数的javascript错误。

我在想,如果它与我如何使用.html()方法获得SVG有关 - 可能什么是返回的不会被解释为一个真正的SVG文件?

任何帮助非常感谢。

function saveImage(){ 

     var img = document.getElementById('canvas').toDataURL("image/png"); 
     window.open(img,'Download'); 

    } 

    $('#save').click(function(){ 

     var svg = $('#editor').html(); 

     // Create new SVG Image element. Must also be careful with the namespaces. 
     var svgimg = document.createElementNS("http://www.w3.org/2000/svg", "image"); 
     svgimg.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', "myimage.jpg"); 


     // Append image to SVG 
     svg.appendChild(svgimg); 

     canvg('canvas', svg, {renderCallback: saveImage(), ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true}); 

    }); 

回答

18

这里是做这件事的一种方法:

var svgimg = document.createElementNS('http://www.w3.org/2000/svg','image'); 
svgimg.setAttributeNS(null,'height','200'); 
svgimg.setAttributeNS(null,'width','200'); 
svgimg.setAttributeNS('http://www.w3.org/1999/xlink','href', 'myimage.jpg'); 
svgimg.setAttributeNS(null,'x','10'); 
svgimg.setAttributeNS(null,'y','10'); 
svgimg.setAttributeNS(null, 'visibility', 'visible'); 
$('svg').append(svgimg); 
+0

热潮。非常感谢你。 –

相关问题