1 function drawBar(data) { 2 var barGraph = document.querySelector("#bar-graph"); 3 var graphWidth = 700; 4 var graphHeight = 300; 5 const graphPadding = 25; 6 //軸的寬高 7 const axisWidth = graphWidth - graphPadding; 8 const axisHeigt = graphHeight - graphPadding; 9 //柱的間隔 10 const barGap = 12; 11 //單個數據柱子的寬 12 const barWidth = ((axisWidth - graphPadding - barGap * 13) / 12) / data.length; 13 //每根柱子的顏色 14 const barColor = ["#27a1ea", "#9cdc82", "#ff9f69", "#d660a8", "#6370de", "#32d3eb", "#d4ec59", "#feb64d", "#b55cbd"]; 15 //軸的顏色 16 const axisColor = "#000"; 17 //最大值 18 var dataMax = 0; 19 //柱狀圖數據sale 20 var newData = []; 21 22 //設置html的svg的寬度和高度 23 barGraph.setAttribute("width", graphWidth); 24 barGraph.setAttribute("height", graphHeight); 25 //找到最大值 26 for (let i = 0; i < data.length; i++) { 27 if (typeof data[0] != "number") { 28 let temp = Math.max(...data[i].sale);//es6擴展運算符 將數組轉為序列。 29 if (temp > dataMax) { 30 dataMax = temp; 31 } 32 newData.push(data[i].sale); 33 } else { 34 dataMax = Math.max(...data); 35 newData.push(data[i]); 36 } 37 } 38 //數據和像素的折算 39 var rate = dataMax / (axisHeigt - graphPadding); 40 //繪制坐標軸 41 let barHtml = []; 42 //先縱軸再橫軸注意SVG畫線模板間隔 43 barHtml.push("<line x1=" + graphPadding + " y1=0" + " x2=" + graphPadding + " y2=" + axisHeigt + " stroke=" + axisColor + " stroke-width='2'/>"); 44 barHtml.push("<line x1=" + graphPadding + " y1=" + axisHeigt + " x2=" + axisWidth + " y2=" + axisHeigt + " stroke=" + axisColor + " stroke-width='2'/>"); 45 //繪制柱狀圖(需要X,Y,寬度,高度)(高度=數值/rate) 46 for (let i = 0; i < newData.length; i++) { 47 for (let j = 0; j < newData[i].length; j++) { 48 let num = parseInt(newData[i][j]); 49 let barBlock = data.length * barWidth; 50 51 let x = graphPadding + (j + 1) * barGap + i * barWidth + j * barBlock; 52 barHtml.push("<rect width=" + barWidth + " height=" + (num / rate) + " x=" + x + " y=" + (axisHeigt - num / rate) + " fill=" + barColor[i] + " />"); 53 } 54 } 55 barGraph.innerHTML = barHtml.join(""); //join("")拼成字符串無間隔 join()默認為逗號, 56 }
今天終於將SVG生成柱狀圖的代碼給完成了,過程中定位比較重要,包括坐標軸的X,Y點,和長度寬度,都需要要好好設計一下。
其中viewbox屬性比較有趣,學習了,貼出鑫旭大神的解說,非常清晰。http://www.zhangxinxu.com/wordpress/?p=4323
在編寫代碼時,記得哪個數組對應哪些數據,實在忘記可用console.log進行打印查看,方便定位
for循環中的i記得要聲明!!
循環拼寫html時,記得對應好SVG的標簽格式,留出適當的空格才正確!
拼接最后的html時,用join(“”),中間不用放任何內容,便可連接html,不能使用join(),否則默認為逗號連接。