动态插入图片到 svg 中使用 createElementNS 来创建svg标签,通过setAttributeNS 来设置属性,
要注意两点,创建的时候要有'http://www.w3.org/2000/svg',创建的标签要有 height width 两个说属性。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title>This is an HTML5 page</title>
<script type="text/javascript">
function test() {
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', 'http://www.mosoteach.cn/images/custom.png');
svgimg.setAttributeNS(null,'x','10');
svgimg.setAttributeNS(null,'y','10');
svgimg.setAttributeNS(null, 'visibility', 'visible');
document.getElementById('svg1').appendChild(svgimg);
}
</script>
</head>
<body>
<button onclick="test();">Add Image Element to SVG</button>
<svg id="svg1" width="600" height="600" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<image xlink:href="http://img.alicdn.com/tps/i4/TB1sLIsGXXXXXb6XFXX1aiKJFXX-4-7.png" x="0" y="0" height="100" width="100" />
</svg>
</body>
</html>