2014-12-02 81 views
0

我对d3和js一般都很陌生,所以请耐心等待:) 我正在使用d3中的树布局,并且拥有以下问题。如何使用json图像作为d3.js节点背景

我试图让我附加在节点上的圆圈显示图像作为背景图像。我已经看到有关如何通过创建模式并将图像添加到其中的相关文章。

在我的情况下,情况稍有不同,因为我需要从json对象中提取图像。换句话说,每个节点都应该有作为背景图像的链接在我的json对象的“image”字段下的相应图像。 JSON对象我的工作看起来像

"people": [{ 
    "name": "John", 
    "parent_id": "123", 
    "image:http://test.test.com/img2.png" 
}, { 
    "name": "Paul", 
    "parent_id": "687", 
    "image:http://test.test.com/img42.png" 
} { 
    "name": "George", 
    "parent_id": "325", 
    "image:http://test.test.com/img85.png" 
} { 
    "name": "Ringo", 
    "parent_id": "163", 
    "image:http://test.test.com/img93.png" 
}] 

所以我试图让后面附加了“环”有背景图像img93.png文本节点...

希望这是有道理的,多亏了所有的事先...

+2

查看http://stackoverflow.com/questions/7306250/does-force-directed-layout-of-d3-js-support-image-as-node – 2014-12-02 17:10:15

+0

@LarsKotthoff,感谢您的及时回复, m试图让每个节点显示相应的图像在数组中,不是所有节点上的相同的一个..不能在建议的帖子中找到解决方案..但我没有得到它?尽管谢谢! :D – 2014-12-02 17:23:13

+2

所以它会是'.attr(“xlink:href”,function(d){return d.image;})'。顺便说一句,你的JSON的格式似乎是错误的,'image'后面的引号和':'后面的引号都丢失了。 – 2014-12-02 18:07:35

回答

0

正如@ LarsKotthoff的回答here建议,将图像定义为模式,然后填充。

var data = [{ 
    "name": "John", 
    "parent_id": "123", 
    "image": "http://placehold.it/50&text=" 
}, { 
    "name": "Paul", 
    "parent_id": "687", 
    "image": "http://placehold.it/50&text=" 
}, { 
    "name": "George", 
    "parent_id": "325", 
    "image": "http://placehold.it/50&text=" 
}, { 
    "name": "Ringo", 
    "parent_id": "163", 
    "image": "http://placehold.it/50&text=" 
}]; 

var svg = d3.select("body") 
    .append("svg") 
    .attr("width", 1000) 
    .attr("height", 150); 

svg.append("defs") 
    .selectAll("pattern") 
    .data(data) 
    .enter() 
    .append("pattern") 
    .attr('id', function(d, i) { 
    return d.name; 
    }) 
    .attr('patternUnits', 'userSpaceOnUse') 
    .attr('width', 50) 
    .attr('height', 50) 
    .append("image") 
    .attr("xlink:href", function(d) { 
    return d.image + d.name; 
    }) 
    .attr('width', 50) 
    .attr('height', 50); 

var circle = svg.selectAll("circle") 
    .data(data) 
    .enter().append("circle") 
    .attr("cy", 70) 
    .attr("cx", function(d, i) { 
    return (i + 1) * 100; 
    }) 
    .attr("r", 50) 
    .attr("fill", function(d) { 
    return "url(#" + d.name + ")"; 
    }); 

示例here