我有一个带有 jpg 图像的网页,用户在使用 Raphael 的基础上绘制了 SVG 涂鸦。
我想允许用户在完成后保存合并的光栅化版本(我将自己用 SVG 版本做其他事情)
当用户单击保存时,我想将该背景图像作为元素添加到生成的 SVG DOM 中,然后使用 canvg 将 SVG 写入 Canvas 元素。最后,我使用 toDataUrl() 方法将其转换为 jpg。
我无法让中间位工作 — 将图像添加到 DOM 的最佳方式是什么?当我使用下面的代码时,我收到一个 javascript 错误,提示 appendChild() 不是一个函数。
我想知道这是否与我使用 .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});
});
最佳答案
这是一种实现方式:
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);
关于javascript - 如何将 <image> 元素添加到 SVG DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859257/