Skip to content

Instantly share code, notes, and snippets.

@shimizu
Created September 15, 2017 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shimizu/bf7f84066d10c71bd61d716500b26a31 to your computer and use it in GitHub Desktop.
Save shimizu/bf7f84066d10c71bd61d716500b26a31 to your computer and use it in GitHub Desktop.
D3.js v4 Pan/Zoom
license: mit
<!DOCTYPE html>
<!-- saved from url=(0035)http://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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment