How do I replace a node with an image using D3 and CoffeeScript for a network visualization?

吃可爱长大的小学妹 提交于 2019-12-04 18:08:14

Why not replacing circles with your image:

node.enter().append("image")
  .attr("class", "node")
  .attr("href", "tinyWhale.jpg")
  .attr("x", function(d) { return d.x;})
  .attr("y", function(d) { return d.y;})
  .attr("width", function(d) { return d.radius;})
  .attr("height", function(d) { return d.radius;})

instead of:

node.enter().append('circle')...
Lars Kotthoff

You can't use images like that directly in SVG, you need to define them as a pattern. See this question for more information. You haven't shown us your code, but I suspect that this is the source of your problem.

What you need to do is append a pattern for each image you need to the defs section of the SVG and then reference those patterns when you add the node. The code would look something like this.

defs = svg.append("defs")
defs.selectAll("pattern")
    .data(curNodesData)
    .append("pattern")
    .attr("id", (d) -> d.group)
    .append("image")
    .attr("xlink:href", (d) -> d.group)

You may need to set the dimensions for the patterns and images. Then later you can do the following

node.enter().append("circle")
    .attr("fill", (d) -> "url(#" + d.group + ")")

You may need to adjust the way the pattern IDs are generated, especially if you start using absolute URLs.

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