asparism
asparism

Reputation: 614

D3 v4 force graph with images as nodes

Having problems using images as nodes in a force-directed graph. Everything I've looked at so far seems to be v3 code and I haven't been able to get any images at all so far, whether using xlink:href or svg:image or both.

What's the right way to use an img as a node with v4?

Here's what I'm trying, and a jsfiddle.

As you can see in the CSS, I'm trying to get images from a spritesheet for each node.

var defs = d3.append("svg:defs");

defs.append("svg:pattern")
      .attr("width", 48)
      .attr("height", 48)
      //.attr("patternUnits", "userSpaceOnUse")
      .append("svg:image")
      .attr("xlink:href", "http://placekitten.com/g/48/48")
      .attr("width", 48)
      .attr("height", 48)
      .attr("x", 0)
      .attr("y", 0);


var nodesDrawn = svg
.selectAll("node")
.data(nodesData)
.enter()
.append("g")
//.append("xhtml:i")
.append('circle')
.attr('r', 10);

Upvotes: 2

Views: 1011

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

The problems so far:

  1. There is no d3.append in D3. You probably meant svg.append.
  2. Set the width and the height of the <pattern> to 1.
  3. Set an ID to the <pattern> and use that to fill the circles.

Here are the code with that changes (I'm increasing the circles' radii, so you can better see the image): https://jsfiddle.net/ppk23hnz/

By the way, none of those changes are related to D3 version: they are the same in v3.x and v4.x.

PS: Don't mix jQuery and D3. you don't need that (and it's quite disturbing).

Upvotes: 2

Related Questions