block by mbostock ffbe45ba1dfc5ebd56b7f4cfdac9b71a

Polygon Clipping II

Full Screen

This example demonstrates how to use d3.geoIdentity and d3.geoProject to clip a polygon to an extent. While this example clips the polygon in the browser, this would more commonly be done on the command-line using geoproject. The advantage of this approach over clipping while rendering is that you can precompute the clipped polygon for faster rendering.

index.html

<!DOCTYPE html>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-geo-projection.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>

var svg = d3.select("svg");

svg.append("rect")
    .attr("fill", "blue")
    .attr("x", 100)
    .attr("y", 100)
    .attr("width", 760)
    .attr("height", 400);

d3.json("https://d3js.org/us-10m.v1.json", function(error, us) {
  if (error) throw error;

  var path = d3.geoPath(),
      clip = d3.geoIdentity().clipExtent([[100, 100], [860, 500]]),
      nation = topojson.feature(us, us.objects.nation),
      nationClipped = d3.geoProject(nation, clip);

  svg.append("path")
      .attr("fill", "red")
      .attr("d", path(nation));

  svg.append("path")
      .attr("fill", "black")
      .attr("stroke", "white")
      .attr("d", path(nationClipped));
});

</script>