1. 程式人生 > >D3生成柱形圖新增滑鼠事件(一)

D3生成柱形圖新增滑鼠事件(一)

 直接上程式碼,這是動態生成的柱形圖,並添加了滑鼠事件

<html>  
  <head>  
        <meta charset="utf-8">  
        <title>8.1.1 滑鼠互動</title>  
  </head> 
  <style>
  
.axis path,
.axis line{
	fill: none;
	stroke: black;
	shape-rendering: crispEdges;
}
 
.axis text {
	font-family: sans-serif;
	font-size: 11px;
}

  </style>
<body>

<script src="../../d3/d3.v4.js" charset="utf-8"></script> 

<script>  

var dataset = [50, 43, 120, 87, 99, 167, 142];

var width  = 400;	//SVG繪製區域的寬度
var height = 400;	//SVG繪製區域的高度
	
var svg = d3.select("body")			//選擇<body>
			.append("svg")			//在<body>中新增<svg>
			.attr("width", width)	//設定<svg>的寬度屬性
			.attr("height", height);//設定<svg>的高度屬性
			
//x軸寬度
var xAxisWidth = 300;

//y軸寬度
var yAxisWidth = 300;
			
//x軸比例尺
var xScale = d3.scaleBand()
				.domain(d3.range(dataset.length))
				.range([0,xAxisWidth]);

//y軸比例尺
var yScale = d3.scaleLinear()
				.domain([0,d3.max(dataset)])
				.range([0,yAxisWidth]);			
	
//外邊框
var padding = { top: 30 , right: 30, bottom: 30, left: 30 };

var rect = svg.selectAll("rect")
				.data(dataset)		//繫結資料
				.enter()			//獲取enter部分
				.append("rect")	//新增rect元素,使其與繫結陣列的長度一致
				.attr("fill","steelblue")		//設定顏色為steelblue
				.attr("x", function(d,i){		//設定矩形的x座標
					return padding.left + xScale(i);
				})
				.attr("y", function(d){		//設定矩形的y座標
					return height- padding.bottom - yScale(d);
				})
				.attr("width",xScale.bandwidth())		//設定矩形的寬度
				.attr("height",function(d){	//設定矩形的高度
					return yScale(d);
				})
				.on("mouseover",function(d,i){
					d3.select(this)
					  .attr("fill","yellow");
				})
				.on("mouseout",function(d,i){
					d3.select(this)
					  .transition()
					  .duration(500)
					  .attr("fill","steelblue");
				});
				
var text = svg.selectAll("text")
				.data(dataset)			//繫結資料
				.enter()				//獲取enter部分
				.append("text")			//新增text元素,使其與繫結陣列的長度一致
				.attr("fill","white")
				.attr("font-size","14px")
				.attr("text-anchor","middle")
				.attr("x", function(d,i){
					return padding.left + xScale(i);
				})
				.attr("y", function(d){
					return height- padding.bottom - yScale(d);
				})
				.attr("dx",xScale.bandwidth()/2)
				.attr("dy","1em")
				.text(function(d){
					return d;
				});

var xAxis = d3.axisBottom(xScale);
				

yScale.range([yAxisWidth,0]);
				
var yAxis = d3.axisLeft(yScale);
				
				
svg.append("g")
		.attr("class","axis")
		.attr("transform","translate(" + padding.left + "," + (height - padding.bottom) +  ")")
		.call(xAxis);
			
svg.append("g")
		.attr("class","axis")
		.attr("transform","translate(" + padding.left + "," + (height - padding.bottom - yAxisWidth) +  ")")
		.call(yAxis); 
	
</script> 

</body>

</html>