Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active Feb 9, 2016
Embed
What would you like to do?
Stretched Projection
license: gpl-3.0

Using d3.geo.projection to create a custom stretched projection to fill a viewport. In this case, the equirectangular projection is stretched to fit a 960×500 viewport.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.land {
fill: #ccc;
}
.country-border {
fill: none;
stroke: #fff;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
height = 500;
var path = d3.geo.path()
.projection(cylindrical(width, height));
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("/mbostock/raw/4090846/world-50m.json", function(error, world) {
if (error) throw error;
svg.append("path")
.datum(topojson.feature(world, world.objects.land))
.attr("class", "land")
.attr("d", path);
svg.append("path")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "country-border")
.attr("d", path);
});
function cylindrical(width, height) {
return d3.geo.projection(function(λ, φ) { return [λ, φ * 2 / width * height]; })
.scale(width / 2 / Math.PI)
.translate([width / 2, height / 2]);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment