動態插入圖片到 svg 中


動態插入圖片到 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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM