Skip to content

Instantly share code, notes, and snippets.

@john-guerra
Last active April 18, 2018 22:01
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 john-guerra/05fafb55db94775db6b40ba62aa02772 to your computer and use it in GitHub Desktop.
Save john-guerra/05fafb55db94775db6b40ba62aa02772 to your computer and use it in GitHub Desktop.
d3.geoPath + Canvas + Zoom + Panning
license: gpl-3.0
height: 600
border: no

Simple example of how to create a d3v4 map with canvas and zoom+panning. There are two ways of achieving this, one is to scale and pan the canvas (the method implemented here), the second way if you are using a projection is to scale and translate the projection instead

Original Readme:

D3’s d3.geoPath can be used with Canvas, not just SVG! This geometry is from us-atlas.

forked from mbostock's block: d3.geoPath + Canvas

<!DOCTYPE html>
<canvas width="960" height="600"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/topojson-client@3"></script>
<script>
var width = d3.select("canvas").property("width"),
height = d3.select("canvas").property("height");
d3.json("https://unpkg.com/us-atlas@1/us/10m.json", function(error, us) {
if (error) throw error;
var context = d3.select("canvas")
.call(d3.zoom()
.scaleExtent([1, 8])
.on("zoom", function () {
redraw(d3.event.transform);
}))
.node().getContext("2d"),
path2D = new Path2D(), //To precompute the path
path = d3.geoPath()
.context(path2D);
path(topojson.mesh(us));
function redraw(transform) {
context.clearRect(0, 0, width, height);
context.save();
if (transform) {
context.translate(transform.x, transform.y);
context.scale(transform.k, transform.k);
}
context.beginPath();
context.stroke(path2D);
context.restore();
}
redraw();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment