block by shimizu bf7f84066d10c71bd61d716500b26a31

D3.js v4 Pan/Zoom

Full Screen

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<!-- saved from url=(0035)//shimz.me/example/d3js/zoom1/ -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>D3.js v4 Pan/Zoom Tutorial</title>
<style>
  html, body {
    padding:0px;
    margin:0px;
  }  
  
svg {
	background-color:floralwhite;
}
</style>

<body>
<p>Zoom(移動:ドラッグ、拡大縮小:ホイール)</p> 
<svg></svg>


<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>    
<script>
var w = 960;
var h = 500;

var data = d3.range(0, 100).map(function(d){
	return {"x": ~~(Math.random() * w ), "y": ~~(Math.random() * h), "r": ~~(Math.random() * 90) + 10 };
});

var svg = d3.select("svg")
	.attr("width", w)
	.attr("height", h)

//ズーム対象とするレイヤーを生成	
var zoomLayer  = svg.append("g")
	
	
//カラージェネレーター
var color = d3.scaleOrdinal(d3.schemeCategory10);



//サークルを配置
zoomLayer.selectAll("circle")
	.data(data)
	.enter()
	.append("circle")
	.attr("cx", function(d){ return d.x })
	.attr("cy", function(d){ return d.y })
	.attr("r", function(d){ return d.r })
	.attr("fill", function(d,i){  return color(i) })
	.attr("fill-opacity", 0.5)
	

//ズーム時の処理を設定
var zoomed = function() {
  zoomLayer.attr("transform", d3.event.transform);
}

//ズームイベントをsvg要素に束縛
svg.call(d3.zoom()
	.scaleExtent([1 / 2, 12])
	.on("zoom", zoomed));	
	
	
</script>	
</body>
</html>