Skip to content

Instantly share code, notes, and snippets.

@sxywu
Last active August 14, 2018 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sxywu/1c389ee88de9ffaecee5c8430d3a3bdf to your computer and use it in GitHub Desktop.
Save sxywu/1c389ee88de9ffaecee5c8430d3a3bdf to your computer and use it in GitHub Desktop.
SVG Dynamic Simplification
license: gpl-3.0

This map dynamically simplifies the geometry in response to zooming, so that the smallest displayed detail is approximately one square pixel. Use the mousewheel, or pinch on touch devices, to zoom.

forked from mbostock's block: Dynamic Simplification IV

<!DOCTYPE html>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/topojson-client@2"></script>
<script src="https://unpkg.com/topojson-simplify@2"></script>
<script>
var svg = d3.select("svg"),
width = svg.property("width"),
height = svg.property("height");
var land,
borders;
var minZ, // minimum area threshold for simplification
transform = d3.geoIdentity().clipExtent([[0, 0], [width, height]]),
simplify = d3.geoTransform({
point: function(x, y, z) { if (z >= minZ) this.stream.point(x, y); }
});
var zoom = d3.zoom()
.scaleExtent([1 / (1 << 5), 1 << 2])
.on("zoom", zoomed);
var path = d3.geoPath()
.projection({stream: function(s) { return simplify.stream(transform.stream(s)); }});
d3.json("us-states.json", function(error, us) {
if (error) throw error;
topojson.presimplify(us);
land = topojson.feature(us, us.objects.states).features;
borders = topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; });
// An arbitrary scale and center point to set the initial view.
// This projection is baked into the TopoJSON file,
// but is used here to compute the desired zoom translate.
// var scale = 0.05, point = d3.geoMercator()
// .translate([0, 0])
// .scale(4000)
// ([-75.959, 38.250]);
// canvas
// .call(zoom)
// .call(zoom.transform, d3.zoomIdentity
// .translate(width / 2, height / 2)
// .scale(scale)
// .translate(-point[0], -point[1]));
console.log(land, borders)
svg.selectAll('path')
.data(land).enter().append('path')
.attr('d', path)
});
function zoomed(d) {
// var t = d3.event.transform;
// minZ = 1 / (t.k * t.k);
// transform.translate([t.x, t.y]).scale(t.k);
// context.clearRect(0, 0, width, height);
// context.beginPath();
// path(land);
// context.fill();
// context.beginPath();
// path(borders);
// context.stroke();
}
</script>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment