2016-02-25 84 views
1

一直在嘗試構建一個平滑漸變的餅圖/圓環圖,但發現它很難做出來。已經花了很多時間,如何解決這個問題仍然沒有任何運氣。我使用d3js庫d3js餅圖梯度

我有類似這樣

enter image description here

的東西,想與漸變填充它,正是這樣

enter image description here

任何意見,如何使它更接近它。也許你們中有人已經面對這個問題,並且有一些關於它的知識。

將不勝感激任何答案和建議。

+0

我同意,這是不是在所有瑣碎的(除非有真可謂是一個SVG建 - 這樣做,我很確定沒有)。即使在Photoshop中這樣做也是一個挑戰。我能想到的達到這種效果的唯一方法是將弧分解成一堆具有固體填充或方向角與弧的切線角相匹配的線性梯度的較小弧段。可行,但不是微不足道的。 – meetamit

+0

你想要在每個「切片」上的漸變或整個事物的漸變? – Mark

+0

@標記是的,正好在整個餡餅上,順利地從一個切片溢出到另一個切片,但它們之間有間隙。 –

回答

2

作爲@meetamit在他的評論中說,沒有內置的SVG方式,我可以找到產品圓形像你顯示的漸變。但是,如果我們建立在這個優秀的answer上,我們可以很好地複製您的圖表。

訣竅是製作一個360弧度的甜甜圈(每個度數一個)來自己創建漸變。然後我們可以使用pie計算,不包括弧在那裏我們片填充應該是:

<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> 
 
    </head> 
 

 
    <body> 
 
    <script> 
 
    
 
     // sample data 
 
     var data = [10,20,30,40,50]; 
 
    
 
     var height = 500, 
 
      width = 500, 
 
      radius = 200, 
 
      padding = 0.04; 
 
     
 
     var svg = d3.select('body') 
 
     .append('svg') 
 
     .attr('width', width) 
 
     .attr('height', height) 
 
     .append('g') 
 
     .attr('transform', 'translate(' + width/2 + ',' + width/2 + ')'); 
 
     
 
     var arc = d3.svg.arc() 
 
     .innerRadius(radius - 100) 
 
     .outerRadius(radius); 
 
     
 
     // pie the data 
 
     var pie = d3.layout.pie() 
 
     .sort(null) 
 
     .value(function(d) { return d; }); 
 
     data = pie(data); 
 

 
     // create our gradient 
 
     var colors = [], 
 
      slice = 0, 
 
      inPad = false; 
 
     // 360 degrees 
 
     d3.range(360).forEach(function(d, i) { 
 
     // convert to radians 
 
     var start = i * (Math.PI/180), 
 
      end = (i + 1) * (Math.PI/180); 
 
     // if we are in a padding area 
 
     if (Math.abs(data[slice].startAngle - start) < padding || 
 
      Math.abs(data[slice].endAngle - start) < padding) { 
 
      inPad = true; 
 
     } else { 
 
      // when to move to next slice 
 
      if (inPad){ 
 
      // move to next slice 
 
      slice++; 
 
      // "stick" on last slice 
 
      if (slice >= data.length) slice = 4; 
 
      } 
 
      inPad = false; 
 
     } 
 
     // only push if not in padding 
 
     if (!inPad){ 
 
      colors.push({ 
 
      startAngle: start, 
 
      endAngle: end, 
 
      fill: d3.hsl(i, 1, .5).toString() 
 
      }); 
 
     } 
 
     }); 
 
     // add arcs 
 
     svg.selectAll('.arc') 
 
     .data(colors) 
 
     .enter() 
 
     .append('path') 
 
     .attr('class', 'arc') 
 
     .attr('d', arc) 
 
     .style('fill', function(d){ 
 
      return d.fill; 
 
     }) 
 
     .style('stroke',function(d){ 
 
      return d.fill; 
 
     }); 
 
    </script> 
 
    </body> 
 

 
</html>