block by curran e857dbe6db49d4cac379855b0b6b58e9

Raster & Vector 4.0

Full Screen

A fork of mbostock‘s block: Raster & Vector III upgraded to use D3 4.0 and d3-tile.

Tiles copyright OpenStreetMap contributors.

web counter

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  margin: 0;
}

path {
  fill: none;
  stroke: red;
  stroke-linejoin: round;
}

</style>
<body>
<script src="//d3js.org/d3.v4.0.0-alpha.50.min.js"></script>
<script src="//d3js.org/d3-tile.v0.0.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>

var width = Math.max(960, window.innerWidth),
    height = Math.max(500, window.innerHeight);

var tile = d3.tile()
    .size([width, height]);

var projection = d3.geoMercator()
    .scale((1 << 12) / 2 / Math.PI)
    .translate([width / 2, height / 2]);

var center = projection([-100, 40]);

var path = d3.geoPath()
    .projection(projection);

var zoom = d3.zoom()
    .scaleExtent([1 << 11, 1 << 14])
    .on("zoom", zoomed);

var initialTransform = d3.zoomIdentity
    .translate(width - center[0], height - center[1])
    .scale(projection.scale() * 2 * Math.PI)

// With the center computed, now adjust the projection such that
// it uses the zoom behavior’s translate and scale.
projection
    .scale(1 / 2 / Math.PI)
    .translate([0, 0]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var raster = svg.append("g");

var vector = svg.append("path");

d3.json("https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/us.json", function(error, us) {
  if (error) throw error;

  svg.call(zoom).call(zoom.transform, initialTransform);
  
  vector.attr("d", path(topojson.mesh(us, us.objects.counties)));
});

function zoomed() {

  var transform = d3.event.transform;
  
  var tiles = tile
      .scale(transform.k)
      .translate([transform.x, transform.y])
      ();

  vector
      .attr("transform", transform)
      .style("stroke-width", 1 / transform.k);
 
  var image = raster
      .attr("transform", "scale(" + tiles.scale + ")translate(" + tiles.translate + ")")
    .selectAll("image")
      .data(tiles, function(d) { return d; });

  image.exit()
      .remove();

  image.enter().append("image")
      .attr("xlink:href", function(d) { return "//" + ["a", "b", "c"][Math.random() * 3 | 0] + ".tile.openstreetmap.org/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; })
      .attr("width", 1)
      .attr("height", 1)
      .attr("x", function(d) { return d[0]; })
      .attr("y", function(d) { return d[1]; });
}

</script>