D3 map can be drawn and colored as shown in this example : http://techslides.com/demos/d3/d3-world-map-zoom-points.html. I need to overlay a texture or image within the boundary of a given country. Is there a way to overlay textures in d3 map ?
1 Answer
Yes - It is possible. I tried using a image texture fill for country polygons in my d3 map. I ended up not using it because of the poor performance I encountered. It caused my slippy d3 map to be unresponsive and cause the browser to slow to a crawl when trying to pan or interact with the map. So, I ended up throwing that code away.
Looking through my code though, I still see a few remnants of my attempt.
For what it's worth, I followed the regular old patterns for using fill textures in SVG: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
So, I created a defs element in my d3 canvas:
var defs = svg.append('svg:defs');
defs.append('svg:pattern')
.attr('id', 'ptnBlueCanvas')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', '278')
.attr('height', '133')
.append('svg:image')
.attr('xlink:href', 'images/background.png')
.attr('x', 0)
.attr('y', 0)
.attr('width', 278)
.attr('height', 133);
...where my image to be used as the fill is referenced using a relative path (images/background.png), which was 278px wide and 133px tall.
After that, I'm struggling to remember what I did. Based on that link i referenced, and other D3 examples that reference using defs for linear gradient fills, I think you reference that def by ID when you set the fill on your polygons.
Check this link on using defs and d3 (but not maps). https://gist.github.com/dholth/1368205
I probably wrote out my polygon features in d3, and then iterated over them using a class selector, and updating the fill attribute. Something like:
.attr('fill', 'url(#ptnBlueCanvas)')
Sorry - I just don't have that code anymore since it wasn't successful.
Hope that nudges you in the right direction.