<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>Test10_D3.js</title>
<!-- d3.js的引用要放在Header內 -->
<script src="d3/d3.min.js"></script>
</head>
<body>
<div id="div1"></div>
<!-- D3.js的Scropt語法要放在Body內 -->
<script>
//新增一個SVG,並設定長、寬
var svg = d3.select("body").append("svg")
.attr("width", 800)
.attr("height", 800)
.append("g")
.attr("transform", "translate(400,400)")
var color = d3.scale.ordinal()
.range(["#abc5c5","#89a68a","#6b5488","#00456c","#aa4400","#6aa560"]);
var dd = [ {v:10,t:"甲"},{v:20,t:"乙"},{v:30,t:"丙"},{v:40,t:"丁"},{v:50,t:"戊"} ];
var arc1 = d3.svg.arc()
.outerRadius(150)
.innerRadius(0);
var pie1 = d3.layout.pie()
.sort(null)
.value(function(d) { return d.v; });
var g1 = svg.selectAll("g")
.data(pie1(dd))
.enter()
.append("g") ;
g1.append("path")
.attr("d", arc1)
.attr("style" ,"fill:none;stroke:black;stroke-width:1;" )
.style("fill", function(d) {
return color(d.data.v);
}) ;
//顯示文字
var t1 = g1.append("text")
.text(function(d) {
console.log(arc1.centroid(d),"arc1.centroid");
return d.data.t;
})
.attr("transform", function(d) {
console.log(arc1.centroid(d),"arc1.centroid");
return "translate(" + arc1.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.attr("fill","red")
.attr("font-size","20px");
//用on綁定事件,指定滑鼠click事件,並撰寫function()來回應click事件
//除了click之外,還有mousedown、mouseup、dblclick、mouseover等
g1.on('click', function () {
//mouse會傳回x、y的值,型態是陣列:[x,y]
x = d3.mouse(this)[0];
y = d3.mouse(this)[1];
console.log(x,y);
//讓文字變顏成綠色,並且放大字體
d3.select(this).select("text")
.attr("fill","green")
.attr("font-size","30px");
});
</script>
</body>
</html>