Skip to content

Instantly share code, notes, and snippets.

@shimizu
Created March 6, 2018 02:31
Show Gist options
  • Save shimizu/b9b7187b75366ab46be12137b05f277b to your computer and use it in GitHub Desktop.
Save shimizu/b9b7187b75366ab46be12137b05f277b to your computer and use it in GitHub Desktop.
D3 v4 - Responsive Globe1
license: mit
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<style>
html, body {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
}
svg {
width: 99%;
height: 99%;
}
</style>
</head>
<body>
<svg></svg>
<script src="//unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
<script src="//unpkg.com/d3@4.12.2/build/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/topojson/3.0.0/topojson.min.js"></script>
<script type="text/babel">
/*地図を表示するステージを追加*/
const stage = d3.select("svg");
const seaLayer = stage.append("g");
const landLayer = stage.append("g");
const projection = d3.geoOrthographic() //投影法を指定
const path = d3.geoPath()//geometryをsvgのパスに変換する関数
d3.json("conuntries.topojson", function(json){ //地図情報の読み込み
const data = topojson.feature(json, json.objects.conuntries).features; //topojson->geojson変換
/*プロジェクション設定*/
projection
.rotate([0,0,0]) //x,y,z回転
.clipAngle(90); //表示する角度 180度を指定すると裏側の大陸まで表示される
/*パスジェネレーターにプロジェクションを設定*/
path.projection(projection);
/*海面を描画するためのパスをDOMに追加*/
seaLayer.append("path")
.datum({type: "Sphere"})
.attr("fill", "blue")
/*地図を表示するためのパスをDOMに追加*/
landLayer
.selectAll("path")
.data(data)
.enter()
.append("path")
.style("background-color", "blue")
.attr("fill", "green")
.attr("stroke", "#222")
.on("mouseover", function(){
d3.select(this).attr("fill", "red");
})
.on("mouseout", function(){
d3.select(this).transition().duration(500).attr("fill", "green");
})
});
/*地形を回転させる*/
const draw = () => {
let i = 0;
return () => {
const w = stage.node().clientWidth;
const h = stage.node().clientHeight;
i = i+0.5;
projection
.rotate([i,0,0]) //rotateのx値を増やして横に回転させる
.scale(d3.min([w, h]) / 2) //画面サイズを元に地球儀の大きさを決定
.translate([w/2, h/2]) //画面中央に表示されるように移動する
path.projection(projection); //path関数をアップデート
seaLayer.select("path").attr("d", path); //海面用パスを描画
landLayer.selectAll("path").attr("d", path); //地図用パスを描画
}
}
setInterval(draw(), 100); //定期的に回転させる
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment