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

不打扰是莪最后的温柔 提交于 2019-11-30 06:57:10
Lars Kotthoff

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

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

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