2014-12-02 57 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