Skip to content

Instantly share code, notes, and snippets.

@syntagmatic
Forked from mbostock/.block
Last active December 22, 2017 12:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save syntagmatic/1092fe86860def004ea7 to your computer and use it in GitHub Desktop.
Save syntagmatic/1092fe86860def004ea7 to your computer and use it in GitHub Desktop.
Hexbin Heightmap
<!DOCTYPE html>
<meta charset="utf-8">
<style>
html, body {
background: #000;
}
svg, canvas {
position: absolute;
top: 0;
left: 0;
}
canvas {
display: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/d3.hexbin.v0.min.js"></script>
<script>
var width = 960,
height = 500;
var hexbin = d3.hexbin()
.size([width, height])
.radius(5);
var color = d3.scale.linear()
.domain([14, 15, 35, 132])
.range(["#333", "#d7191c", "#ffffbf", "#2c7bb6"])
.interpolate(d3.interpolateHcl);
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var points = [];
var hexagons = [];
getImage("readme.png", function(image) {
context.drawImage(image, 0, 0, width, height);
image = context.getImageData(0, 0, width, height);
// Rescale the colors.
for (var c, i = 0, n = width * height * 4, d = image.data; i < n; i += 4) {
points.push([i/4%width, Math.floor(i/4/width), d[i]]);
}
hexagons = hexbin(points);
hexagons.forEach(function(d) {
d.mean = d3.mean(d, function(p) { return p[2]; });
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var hexagon = svg.append("g")
.attr("class", "hexagons")
.selectAll("path")
.data(hexagons)
.enter().append("path")
.attr("d", hexbin.hexagon(4.5))
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.style("fill", function(d) { return color(d.mean); });
});
function getImage(path, callback) {
var image = new Image;
image.onload = function() { callback(image); };
image.src = path;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment