2

I am working on a d3.js force diagram application. I am curious to know how I would go about replacing the central blue circle with an image. Have an image url populate the background of the circle - so have a circular picture?

http://jsfiddle.net/LsMZp/1/

so instead of fill - would it be possible to use just a background url?

    var circle = svg.append("svg:g").selectAll("circle").data(force.nodes()).enter().append("svg:circle").attr("r", function(d) {
        return getRadius(d);
    }).style("fill", function(d) {
        return color(d.group);
    }).call(force.drag);
VividD
  • 10,456
  • 6
  • 64
  • 111
The Old County
  • 89
  • 13
  • 59
  • 129

2 Answers2

1

You can do so by defining a pattern:

<svg>
  <defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image xlink:href="http://www.telascupece.com.br/image/chapa_perfurada.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
  </defs>
</svg>

And then using it in your circle fill:

var circle = svg.append("svg:g")
  .selectAll("circle")
  .data(force.nodes())
  .enter()
  .append("svg:circle")
  .attr("r", function(d) {
    return getRadius(d);
  })
  .style("fill", function(d) {
    return "url(#img1)";
  })
  .call(force.drag);

See updated example: http://jsfiddle.net/LsMZp/2/

enter image description here

VividD
  • 10,456
  • 6
  • 64
  • 111
iros
  • 1,055
  • 1
  • 7
  • 8
1

If you don't require your image to be clipped outside of a circle (I am unsure whether this is what you want or not), you could define a new group of elements:

var image = svg.selectAll(".image");
// Bind to data
image = image.data(force.nodes());
image.enter().append("image")
 .attr("xlink:href", "<url to your image here>")
 .attr("class", "image");

And then in your tick function

function tick() {
    link.attr("x1", function(d) {return d.source.x;})
        .attr("y1", function(d) {return d.source.y;})
        .attr("x2", function(d) {return d.target.x;})
        .attr("y2", function(d) {return d.target.y;});
    node.attr("cx", function(d) {return d.x})
        .attr("cy", function(d) {return d.y});
    image.attr("transform", function(d) {
        return "translate(" + d.x + "," + d.y + ")";
    });
}
Barnabé Monnot
  • 1,163
  • 1
  • 9
  • 19