Can I use images as the background rectangles for d3 treemaps?

Matt picture Matt · Sep 26, 2013 · Viewed 19.4k times · Source

Is it possible to make a treemap in d3 with the background of each rectangle be an image? I am looking for something similar to what was done in Silverlight here, but for d3. If it is possible, are there any recommended tutorials that walk through the process of connecting the background to an image?

Answer

Lars Kotthoff picture Lars Kotthoff · Sep 26, 2013

Yes, there are several ways of using images in SVGs. You probably want to define the image as a pattern and then use it to fill the rectangle. For more information, see e.g. this question (the procedure is the same regardless of the element you want to fill).

In D3 code, it would look something like this (simplified).

svg.append("defs")
   .append("pattern")
   .attr("id", "bg")
   .append("image")
   .attr("xlink:href", "image.jpg");

svg.append("rect")
   .attr("fill", "url(#bg)");