Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d3.js

treemap

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?

like image 532
Matt Avatar asked Sep 26 '13 15:09

Matt


3 Answers

Its important to note, that the image needs to have width, height attributes

chart.append("defs")
                  .append('pattern')
                    .attr('id', 'locked2')
                    .attr('patternUnits', 'userSpaceOnUse')
                    .attr('width', 4)
                    .attr('height', 4)
                   .append("image")
                    .attr("xlink:href", "locked.png")
                    .attr('width', 4)
                    .attr('height', 4);
like image 63
The Old County Avatar answered Oct 23 '22 18:10

The Old County


Using patterns to add an image in a rectangle can make your visualisation quite slow.

You can do something like that instead, this is the code I used for my rectangular nodes into a force layout, I wanted to put rectangles filled by an image as nodes:

var node = svg.selectAll(".node")
    .data(force.nodes())
    .enter().append("g")
    .attr("class", "node");

node.append("rect")
    .attr("width", 80)
    .attr("height", 120)
    .attr("fill", 'none')
    .attr("stroke", function (d) {
        return colors(d.importance);
    }); 

node.append("image")
    .attr("xlink:href", function (d) { return d.cover;})
    .attr("x", 2)
    .attr("width", 76)
    .attr("height", 120)
    .on('dblclick', showInfo);
like image 27
Audrey San Avatar answered Oct 23 '22 19:10

Audrey San


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)");
like image 8
Lars Kotthoff Avatar answered Oct 23 '22 19:10

Lars Kotthoff