2012-06-02 71 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

熱潮。非常感謝你。 –

相關問題