預備內容
深入理解 SVG 系列(一) —— SVG 基礎
深入理解 SVG 系列(二) —— SVG 座標系統
注意 :SVG 中,x 軸的正方向是水平向右,y 軸的正方向是垂直向下的。
柱狀圖
<!--
@author Semper_Fi
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<title></title>
<style>
</style>
</head>
<body>
<svg>
</svg>
</body>
<script>
var rectHeight = 20; // 柱體的寬度
var rectSet = [ 100 , 200 , 170 , 130 , 50 ]; // 柱體的長度
var svg = d3.select("body").select("svg");
svg.selectAll("rect")
.data(rectSet)
.enter()
.append("rect")
.attr("x",20)
.attr("y", function(val, index){
return index * rectHeight;
})
.attr("width", function(val){
return val;
})
.attr("height", rectHeight - 2)
.attr("fill", "blue");
svg.selectAll("rect") //選擇svg內所有的矩形
.data(rectSet) //綁定數組
.append("rect") //添加同數組長度相同數量的矩形元素
</script>
</html>
等同於svg中的
<!DOCTYPE html>
<html>
<body>
<svg>
<rect x="20" y="20" width="100" height="18" style="fill:blue" />
<rect x="20" y="40" width="120" height="18" style="fill:blue" />
<rect x="20" y="60" width="170" height="18" style="fill:blue" />
<rect x="20" y="80" width="50" height="18" style="fill:blue" />
</svg>
</body>
</html>