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.
Created
January 23, 2017 18:13
-
-
Save mbostock/ffbe45ba1dfc5ebd56b7f4cfdac9b71a to your computer and use it in GitHub Desktop.
Polygon Clipping II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 | |
height: 600 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment