javascript 如何将 <image> 元素添加到 SVG DOM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10859257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add an <image> element to the SVG DOM
提问by Danny Browne
I have a web page with a jpg image that the user draw an SVG doodle on top of using Raphael.
我有一个带有 jpg 图像的网页,用户在使用 Raphael 的基础上绘制了一个 SVG 涂鸦。
I want to allow the user to save a merged rasterised version of this when they are done (i will be doing something else with SVG version myself)
我想允许用户在完成后保存合并的光栅化版本(我自己会用 SVG 版本做其他事情)
When the user clicks save I want to add that background image to the generated SVG DOM as an element and then use canvg to write the SVG to a canvas element. Finally I use the toDataUrl() method to turn that into a jpg.
当用户单击保存时,我想将该背景图像作为元素添加到生成的 SVG DOM 中,然后使用 canvg 将 SVG 写入画布元素。最后,我使用 toDataUrl() 方法将其转换为 jpg。
I can't get the middle bit to work —what is the best way to add the image to the DOM? When i use the below code I get a javascript error that says appendChild() is not a function.
我无法让中间部分工作 - 将图像添加到 DOM 的最佳方法是什么?当我使用下面的代码时,我收到一个 javascript 错误,指出 appendChild() 不是一个函数。
I am wondering if it has something to do with how I get the SVG using the .html() method —perhaps what ever is returned is not being interpreted as a real SVG document??
我想知道它是否与我如何使用 .html() 方法获取 SVG 有关 - 也许返回的内容没有被解释为真正的 SVG 文档?
Any help much appreciated.
非常感谢任何帮助。
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});
});
回答by undefined
Here is one way of doing it:
这是一种方法:
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);