Skip to content

Instantly share code, notes, and snippets.

@lorenzopub
Created May 8, 2017 06:18
Show Gist options
  • Save lorenzopub/e86dbe0f5fbe57d4482d1971922f015e to your computer and use it in GitHub Desktop.
Save lorenzopub/e86dbe0f5fbe57d4482d1971922f015e to your computer and use it in GitHub Desktop.
Flatten sphere w/ d3 and svg path transitions!
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">
<style>
path {
fill: none;
stroke-linejoin: round;
}
.graticule {
stroke: #aaa;
}
.equator {
stroke: red;
stroke-width: 2px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://d3js.org/d3.geo.projection.v0.min.js" type="text/javascript"></script>
<script src="http://d3js.org/topojson.v1.js"></script>
<script>
var width = 1060,
height = 600;
var g1 = d3.geo.orthographic()
.rotate([10, -10])
.center([-10, 10])
.scale(240)
.translate([width / 2, height / 2]);
var g2 = d3.geo.equirectangular()
.scale(153)
.translate([width / 2, height / 2]);
var proj = interpolatedProjection(g1, g2);
var patx = d3.geo.path().projection(proj);
var graticule = d3.geo.graticule();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var feature = svg.selectAll("path");
d3.json('brazilWor.json',function(world){
var feat = topojson.feature(world,world.objects.countries110).features;
svg.selectAll('.coun').data(feat).enter().append('path')
.attr('d',patx)
.attr('class','coun')
.style('fill','blue');
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", patx);
var cord = [[-180, 0], [-90, 0], [0, 0], [90, 0], [180, 0]];
svg.append("path").datum({type: "LineString", coordinates: cord})
.attr("class", "equator")
.attr("d", patx);
feature = svg.selectAll("path");
animation();
})
function animation() {
svg.transition()
.duration(10500)
.tween("projection", function() {
return function(_) {
animation.alpha(_);
feature.attr("d", patx);
};
});
}
function interpolatedProjection(a, b) {
var px = d3.geo.projection(raw).scale(1), α;
function raw(λ, φ) {
var pa = a([λ *= 180 / Math.PI, φ *= 180 / Math.PI]), pb = b([λ, φ]);
return [(1 - α) * pa[0] + α * pb[0], (α - 1) * pa[1] - α * pb[1]];
}
animation.alpha = function(_x) {
if (!arguments.length) return α;
α = +_x;
var ca = a.center(), cb = b.center(),
ta = a.translate(), tb = b.translate();
console.log(α, ca, cb);
px.center([(1 - α) * ca[0] + α * cb[0], (1 - α) * ca[1] + α * cb[1]]);
px.translate([(1 - α) * ta[0] + α * tb[0], (1 - α) * ta[1] + α * tb[1]]);
return px;
};
animation.alpha(0);
return px;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment