2014-10-17 14 views
2

而不是piedata變量填充文本,因爲它是現在,我需要有5個不同的圖像的hrefs。現在我只有一個,它在下面被硬編碼,而不是從變量piedata中拉出來。如何添加不同的圖像,而不是文本內d3.js餅圖切片

我還需要在圓的中心有一個圖像。想法,請

<!DOCTYPE html> 
<meta charset="utf-8"> 



<script src="http://d3js.org/d3.v3.min.js" ></script> 



<head> 

</head> 


<body> 
<style> 

path { 
stroke: #fff; 
fill-rule: evenodd; 
} 

text { 
font-family: Arial, sans-serif; 
font-size: 12px; 
} 

</style> 

<script> 


var width = 550, 
    height = 550, 
    radius = 250 
    colors = d3.scale.ordinal() 
     .range(['#336699 ','#336699 ','#ACD1E9','#ACD1E9','#ACD1E9']); 

var piedata = [ 
    { label: "test", 
     value: 50 }, 
    { label: "", 
    value: 50}, 
    { label: "Jonathan", 
    value: 50}, 
    { label: "Lorenzo", 
    value: 50}, 
    { label: "Hillary", 
    value: 50} 
    ] 


var pie = d3.layout.pie() 
    .value(function(d) { 
    return d.value; 
    }) 

var arc = d3.svg.arc() 
    .outerRadius(250) 
    .innerRadius(100) 


var svg = d3.select('body').append('svg') 
    .attr('width', width) 
    .attr('height', height) 
    .append('g') 
    .attr('transform', 'translate('+(width-radius)+','+(height-radius)+')') 
    .selectAll('path').data(pie(piedata)) 
    .enter().append('g') 
    .attr('class', 'slice') 

var slices = d3.selectAll('g.slice') 
    .append('path') 
    .attr('fill', function(d, i) { 
     return colors(i); 
    }) 
     .attr('d', arc) 




var imgs = svg.selectAll("image").data([0]) 
      imgs.enter() 
      .append("svg:image") 
      .attr("xlink:href", "http:/images/home-activities_09.jpg") 
      .attr("x", "110") 
      .attr("y", "35") 
      .attr("width", "40") 
      .attr("height", "40"); 

+0

任何運氣?我也需要同樣的幫助。 – 2014-11-14 03:11:46

+0

這個答案可能有幫助:http://stackoverflow.com/a/26692484/3442309。只要將'.innerRadius(r-100)'改成'.innerRadius(0)'就可以從圓環圖轉換到正常的餅圖 – 2014-11-16 22:58:04

回答

2

如果所有圖片都是恆定的寬度和高度,你只需將圖片網址添加到您的數據陣列和動態設置的XLink:使用數據功能href屬性。

var piedata = [ 
{ 
    label: "test", 
    image: "http://placeimg.com/40/40/any", 
    value: 50 
}, 
{ 
    label: "", 
    image: "http://placeimg.com/42/42/any", 
    value: 50 
}, 
{ 
    label: "Jonathan", 
    image: "http://placeimg.com/44/44/any", 
    value: 50 
}, 
{ 
    label: "Lorenzo", 
    image: "http://placeimg.com/46/46/any", 
    value: 50 
}, 
{ 
    label: "Hillary", 
    image: "http://placeimg.com/38/38/any", 
    value: 50 
} 
] 
.... 
g.append("g") 
    .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; }) 
.append("svg:image") 
    .attr("xlink:href",function(d) {return d.data.image;}) 
    .attr("width",image_width) 
    .attr("height",image_height) 
    .attr("x",-1*image_width/2) 
    .attr("y",-1*image_height/2); 

這裏的工作小提琴:http://jsfiddle.net/LLwr4q7s/

如果,另一方面,每個圖像的大小不同,你不知道什麼是寬度和高度值是事前,一些額外的工作是參與。一種方法是預加載圖像,以便在加載圖像後知道寬度和高度值,並使用回調函數將它們放置在餅圖中。

這裏的動態圖像尺寸的例子小提琴:http://jsfiddle.net/LLwr4q7s/2/