Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Forked from jasondavies/README.md
Created February 28, 2024 05:58
Show Gist options
  • Save mdsumner/576a8ed652c4cf45eac7320ab13c8e1f to your computer and use it in GitHub Desktop.
Save mdsumner/576a8ed652c4cf45eac7320ab13c8e1f to your computer and use it in GitHub Desktop.
Adaptive Resampling

D3 2.11’s d3.geo.path will automatically cut features for any aspect. Try dragging to rotate the world and see a new aspect.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: sans-serif;
}
#precision-wrapper {
position: absolute;
top: 5px;
left: 5px;
}
svg {
cursor: move;
}
rect {
fill: none;
}
.graticule {
fill: none;
stroke: #666;
stroke-width: .5px;
}
.graticule:nth-child(2n) {
stroke-dasharray: 2,2;
}
path.resample {
stroke: #f00;
stroke-width: 2.5px;
fill: none;
}
</style>
<p id="precision-wrapper">Precision: <span id="precision"></span>
<script src="https://raw.github.com/jasondavies/d3/projection/d3.v2.min.js"></script>
<script>
var width = 960,
height = 500,
x = d3.scale.linear().domain([0, width]).range([200, 1]);
var projection = d3.geo.mercator()
.translate([width / 2 - .5, height / 2 - .5])
.scale(400)
.precision(x.range()[0]),
path = d3.geo.path().projection(projection),
graticule = d3.geo.graticule(),
format = d3.format(",.2f"),
precision = d3.select("#precision");
var svg = d3.select("body").append("svg")
.datum({x: 0, y: 0})
.attr("width", width)
.attr("height", height)
.call(d3.behavior.drag()
.origin(Object)
.on("drag", function(d) {
d.x = d3.event.x;
d.y = d3.event.y;
projection.rotate([d.x, -d.y, 0]);
svg.selectAll("path").attr("d", path);
}))
.on("mousemove", function() {
var px = x(d3.mouse(this)[0]);
projection.precision(px);
precision.text(format(px) + "px");
svg.selectAll("path").attr("d", path);
});
svg.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("path")
.attr("class", "resample")
.datum({type: "LineString", coordinates: [[-180, 0], [-90, 0], [0, 0], [90, 0], [180, 0]]})
.attr("d", path);
svg.selectAll(".graticule")
.data(graticule.lines)
.enter().append("path")
.attr("class", "graticule")
.attr("d", path);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment