Skip to content

Instantly share code, notes, and snippets.

@richardwestenra
Created June 25, 2015 10:22
Show Gist options
  • Save richardwestenra/96e20ca73b6e2ac35d82 to your computer and use it in GitHub Desktop.
Save richardwestenra/96e20ca73b6e2ac35d82 to your computer and use it in GitHub Desktop.
d3.geo.path + canvas + pattern image fill
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.min.js"></script>
<script>
var width = 960,
height = 500;
var projection = d3.geo.albers()
.scale(1000);
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var path = d3.geo.path()
.projection(projection)
.context(context);
d3.json("us.json", function(error, us) {
if (error) { throw error; }
var imageObj = new Image();
imageObj.onload = function() {
var pattern = context.createPattern(imageObj, 'repeat');
path(topojson.feature(us, us.objects.counties));
context.fillStyle = pattern;
context.fill();
};
imageObj.src = 'http://lorempixel.com/output/abstract-q-c-640-480-6.jpg';
});
</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