js創建svg元素的方法
阿新 • • 發佈:2019-01-02
svg 添加屬性 ref maximum pre case 報錯 faq initial
需要JQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″/> <link rel="stylesheet" href="http://v3.faqrobot.org/hvb/com/css/reset.css?dev=1"> <script type="text/javascript" src="http://v3.faqrobot.org/hvb/com/js/jquery-1.11.3.min.js?dev=1"></script> <script type="text/javascript" src="http://v3.faqrobot.org/hvb/com/js/base.js?dev=1"></script> <title>svg</title> <style> body, html { width: 100%; height: 100%; } </style> </head> <body> <svg width="400" height="300" viewBox="0 0 400 300"> <path id="textPath" d="M10,10 L40,60 L20,80 L60,90 L70,20 Z" stroke="red" fill="none"></path> <text stroke="red" fill="green" font-size="30" font-family="Microsoft YaHei"></text> </svg> <script> ;$(function() { //創建圓 var $circle = createSvg(‘circle‘, { ‘cx‘: ‘50‘, ‘cy‘: ‘50‘, ‘r‘: ‘20‘, }).appendTo(‘svg‘); //創建文本路徑 var $textPath = createSvg(‘textPath‘, { ‘xlink:href‘: ‘#textPath‘, }).text(‘123456‘).appendTo(‘text‘); //創建svg相關元素 function createSvg(tag, attr) { if(!document.createElementNS) return;//防止IE8報錯 var $svg = $(document.createElementNS(‘http://www.w3.org/2000/svg‘, tag)); for(var key in attr) { switch(key) { case ‘xlink:href‘://文本路徑添加屬性特有 $svg[0].setAttributeNS(‘http://www.w3.org/1999/xlink‘, key, attr[key]); break; default: $svg.attr(key, attr[key]); } } return $svg; }; }); </script> </body> </html>
js創建svg元素的方法