JS在HTML頁面內動態建立SVG元素
阿新 • • 發佈:2019-01-14
最近在學習資料視覺化,深入瞭解瞭如何在網頁上實現資料的動態視覺化。比如D3.JS主要應用JS在HTML頁面內動態生成SVG元素並繫結資料。
以下是我的例程:
<!DOCTYPE html> <HTML> <HEAD> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,target-densitydpi=high-dpi,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0, user-scalable=no"/> <TITLE></TITLE> <STYLE TYPE="TEXT/CSS"> </STYLE> <SCRIPT TYPE="TEXT/JAVASCRIPT"> </SCRIPT> </HEAD> <BODY> <script> //通過createElementNS建立svg元素並設定屬性 var svg=document.createElementNS('http://www.w3.org/2000/svg','svg'); svg.setAttribute("style","width:100%;height:100%;"); svg.setAttribute("viewBox","0 0 100 100"); //建立矩形元素並設定屬性 var rect=document.createElementNS('http://www.w3.org/2000/svg','rect'); rect.setAttribute("x","10"); rect.setAttribute("y","10"); rect.setAttribute("width","20"); rect.setAttribute("height","20"); rect.setAttribute("style","fill:#ff6666;stroke-width:1;stroke:rgb(255,0,0)"); //矩形元素繫結滑鼠事件實現動態效果 rect.onmouseover=function(){ this.setAttribute("style","fill:rgb(225,0,0);stroke-width:1;stroke:rgb(255,102,102)"); } rect.onmouseout=function(){ this.setAttribute("style","fill:#ff6666;stroke-width:1;stroke:rgb(255,0,0)"); } //使用path建立扇形元素 var fan=document.createElementNS('http://www.w3.org/2000/svg','path'); fan.setAttribute("d","M0 0 L10 0 A10 10 90 0 1 0 10"); fan.setAttribute("style","fill:green;"); //扇形元素繫結滑鼠事件實現動態效果 fan.onmouseover=function(){ this.setAttribute("style","fill:yellow;"); } fan.onmouseout=function(){ this.setAttribute("style","fill:green;"); } //將矩形和扇形元素新增到SVG元素內 svg.appendChild(rect); svg.appendChild(fan); //SVG元素新增到頁面內顯示 document.body.appendChild(svg); </script> </BODY> </HTML>