我有一个对象数组。这些对象包含一组名为" x"的属性。和" y"。现在,当我遍历数组时,我将每个对象的圆附加到数组中,将这些坐标作为圆的中心。现在,我想添加随机选择的多边形,如星形/五边形/六边形/圆形等,而不是为每个数据点附加圆形。如何在d3中执行此操作? (PS:我坚持选择和随机附加多边形的逻辑,以及如何使用Array中遍历对象的坐标选择绘制多边形的点)
我目前的代码是:
var data=[
{"x":"100","y":"20","index":"1"},
{"x":"150","y":"22","index":"2"},
{"x":"200","y":"100","index":"3"},
{"x":"210","y":"40","index":"4"},
{"x":"300","y":"30","index":"5"}
];
var svgHeight=800;
var svgWidth=800;
var margin=50;
var divelement=d3.select("body")
.append("div")
.attr("height",svgHeight)
.attr("width",svgWidth)
.attr("style","border:1px solid black;");
var svgElement=divelement.append("svg")
.attr("height",svgHeight)
.attr("width",svgWidth);
var boxGroupElement=svgElement.append("g")
.attr("transform","translate("+margin+","+margin+")");
boxGroupElement.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("d", d3.svg.symbol().size(200).type(function(d){
return d.index%6;
}))
.attr("fill","yellow")
.attr("stroke","blue");
答案 0 :(得分:2)
我知道它并不是非常漂亮,但您可以使用d3.svg.symbol()
:
boxGroupElement.append("path")
.attr("transform", function(d) { return "translate("
+ data[a].x + "," + data[a].y + ")"; })
.attr("d", d3.svg.symbol().size(200).type(d3.svg.symbolTypes[~~(Math.random()
* d3.svg.symbolTypes.length)]))
.attr("fill","yellow")
.attr("stroke","blue");
这是小提琴:https://jsfiddle.net/gerardofurtado/sk1jqary/1/。我冒昧地改变你的数据只是为了将符号分开一点。
当我使用符号的随机数时,每次点击“运行”时,都会出现一组新的符号。
这是API:https://github.com/d3/d3/wiki/SVG-Shapes#symbol。符号是:
正如我所说,不是很漂亮......但您可以使用polygon
创建自己的多边形并附加它们:https://github.com/d3/d3/wiki/SVG-Shapes#svg_polygon