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

天涯浪子 提交于 2019-11-29 08:12:07

问题


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?


回答1:


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)");



回答2:


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);



回答3:


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);


来源:https://stackoverflow.com/questions/19033034/can-i-use-images-as-the-background-rectangles-for-d3-treemaps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!