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

前端 未结 3 1389
难免孤独
难免孤独 2020-12-30 08:36

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

相关标签:
3条回答
  • 2020-12-30 09:00

    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)");
    
    0 讨论(0)
  • 2020-12-30 09:05

    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);
    
    0 讨论(0)
  • 2020-12-30 09:10

    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);
    
    0 讨论(0)
提交回复
热议问题