【问题标题】:Generated color of voronoi polygon in D3.js在 D3.js 中生成 voronoi 多边形的颜色
【发布时间】:2017-09-11 04:11:38
【问题描述】:

我正在尝试在为每个 voronoi 单元生成的 0-999 十六进制字段中创建一个随机多边形颜色。

现在我有随机颜色,但每个单元格都需要它。

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

【问题讨论】:

  • 我已经索引了颜色,我正在尝试访问它们,在 d3 中为每个单元格生成的数组都有一个点和颜色 (x , y , #0-999)
  • @hughes 不太重复,因为对于 d3 voronoi,style:fill 与多边形 svg 相关,而不是单个路径元素。
  • 我确实在互联网上搜索了 2 天,然后才羞愧地问了这个问题。

标签: javascript d3.js


【解决方案1】:

所以这里的原因是,如果您以 .polygons 类为目标,它就是 d3 路径的容器。所以你需要做的是创建一个函数来返回一个随机的十六进制代码(有一个 d3,但为了演示,我使用了来自this stack answer 的一个)。

迭代每个路径元素,并将polygon.style.fill 设置为随机颜色返回。砰!每条路径的颜色随机。

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    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")	
var sites = d3.range(300)
	.map(function(d){return[Math.random()*(width/2)+100,
							Math.random()*(height/2)+100,
							"#"+Math.round(Math.random()*999)]})	
var voronoi = d3.voronoi();
var polygon = svg.append("g")
    .attr("class", "polygons")
	.style("stroke", "tan")
	.style("stroke-width", 0.2)
	.selectAll("path")
	.data(voronoi.polygons(sites))
	.enter().append("path")
    .call(redrawPolygon)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多