2017-04-14 46 views
1

我正在嘗試爲每個voronoi單元格生成的0-999範圍內的十六進制字段創建一個隨機多邊形顏色。在D3.js中生成voronoi多邊形的顏色

現在我有顏色隨機化,但它是每個細胞所必需的。

var voronoi = d3.voronoi() 
 
var svg = d3.select("svg"), 
 
    width = +svg.attr("width"), 
 
    height = +svg.attr("height") \t 
 
var sites = d3.range(300) 
 
\t .map(function(d){return[Math.random()*(width/2)+100, 
 
\t \t \t \t \t \t \t Math.random()*(height/2)+100, 
 
\t \t \t \t \t \t \t "#"+Math.round(Math.random()*999)]}) \t 
 
var voronoi = d3.voronoi() 
 
var polygon = svg.append("g") 
 
    .attr("class", "polygons") 
 
\t .style("stroke", "tan") 
 
\t .style("stroke-width", 0.2) 
 
\t .selectAll("path") 
 
\t .data(voronoi.polygons(sites)) 
 
\t .enter().append("path") 
 
    .call(redrawPolygon) 
 
\t .style("fill", "beige") \t 
 
function redrawPolygon(polygon) { 
 
\t polygon.attr("d",function(d) { return d ? "M" + d.join("L") + "Z" : null; }) 
 
}
<svg width="1000" height="1000"> 
 
\t \t </svg> 
 
\t \t \t <h1>d3</h1> 
 
\t \t \t \t <script src="https://d3js.org/d3.v4.min.js"></script> 
 
\t \t \t \t <script src="1104.js"></script>

+0

[在d3.js圖表​​隨機顏色爲界]的可能的複製(http://stackoverflow.com/questions/13563471/random-colors-for-circles-in-d3 -js-graph) – hughes

+0

我已經有了索引的顏色,我試圖訪問它們,爲每個單元格在d3中生成的數組有一個點和顏色(x,y,#0-999) – Chris

+1

@hughes不完全重複,因爲對於d3 voronoi's,'style:fill'涉及多邊形svg,而不是單個路徑元素。 –

回答

2

所以這裏的原因是,如果您定位.polygons類,它是爲D3路徑的容器。所以你需要做的是創建一個函數來返回一個隨機的十六進制代碼(有一個d3,但爲了演示的目的,我使用了this stack answer中的一個)。

迭代每個路徑元素,並將polygon.style.fill設置爲隨機顏色返回。巴姆!每個路徑的隨機顏色。

function getRandomColor() { 
 
    var letters = 'ABCDEF'; 
 
    var color = '#'; 
 
    for (var i = 0; i < 6; i++) { 
 
     color += letters[Math.floor(Math.random() * 16)]; 
 
    } 
 
    return color; 
 
} 
 

 
var voronoi = d3.voronoi() 
 
var svg = d3.select("svg"), 
 
    width = +svg.attr("width"), 
 
    height = +svg.attr("height") \t 
 
var sites = d3.range(300) 
 
\t .map(function(d){return[Math.random()*(width/2)+100, 
 
\t \t \t \t \t \t \t Math.random()*(height/2)+100, 
 
\t \t \t \t \t \t \t "#"+Math.round(Math.random()*999)]}) \t 
 
var voronoi = d3.voronoi(); 
 
var polygon = svg.append("g") 
 
    .attr("class", "polygons") 
 
\t .style("stroke", "tan") 
 
\t .style("stroke-width", 0.2) 
 
\t .selectAll("path") 
 
\t .data(voronoi.polygons(sites)) 
 
\t .enter().append("path") 
 
    .call(redrawPolygon) 
 

 
document.querySelectorAll("path").forEach(polygon => polygon.style.fill = getRandomColor()); 
 

 
function redrawPolygon(polygon) { 
 
\t polygon.attr("d",function(d) { return d ? "M" + d.join("L") + "Z" : null; }) 
 
}
<svg width="1000" height="1000"> 
 
\t \t </svg> 
 
\t \t \t <h1>d3</h1> 
 
\t \t \t \t <script src="https://d3js.org/d3.v4.min.js"></script> 
 
\t \t \t \t <script src="1104.js"></script>