Javascript D3 JS单击生成多边形

Javascript D3 JS单击生成多边形,javascript,d3.js,Javascript,D3.js,考虑以下代码 var width = 960, height = 500; var vertices = d3.range(100).map(function(d) { return [Math.random() * width, Math.random() * height]; }); var voronoi = d3.geom.voronoi() .clipExtent([[0, 0], [width, height]]); var svg = d3.select(

考虑以下代码

var width = 960,
    height = 500;

var vertices = d3.range(100).map(function(d) {
  return [Math.random() * width, Math.random() * height];
});

var voronoi = d3.geom.voronoi()
    .clipExtent([[0, 0], [width, height]]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .on("mousemove", function() { vertices[0] = d3.mouse(this); redraw(); });


var path = svg.append("g").selectAll("path");

svg.selectAll("circle")
    .data(vertices.slice(1))
  .enter().append("circle")
    .attr("transform", function(d) { return "translate(" + d + ")"; })
    .attr("r", 1.5);

redraw();

function redraw() {
  path = path
      .data(voronoi(vertices), polygon);

  path.exit().remove();

  path.enter().append("path")
      .attr("class", function(d, i) { return "q" + (i % 9) + "-9"; })
      .attr("d", polygon);

  path.order();
}

function polygon(d) {
  return "M" + d.join("L") + "Z";
}

如何在单击的同时添加一个新多边形&同时绘制一个中心点?

您有一个良好的开始。除了
svg
上的
mousemove
监听器之外,您还需要一个
单击
监听器。使用此功能,您可以在用户每次单击时添加一个新顶点。为此,我向redraw函数添加了一个变量,以区分单击触发的重画。你也许能找到一个更干净的方法来做这件事,但希望这能有所帮助

var-width=960,
高度=500;
变量顶点=d3.范围(100).映射(函数(d){
返回[Math.random()*宽度,Math.random()*高度];
});
var voronoi=d3.geom.voronoi()
.clipExtent([[0,0],[width,height]]);
var svg=d3.选择(“正文”).追加(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度)
.on(“mousemove”,function(){texts[0]=d3.mouse(this);redraw();})
.on('click',function(){
顶点.push(d3.mouse(this));
重画(真);
});
var path=svg.append(“g”).selectAll(“path”);
var circle=svg.selectAll(“circle”);
重画();
函数重画(从单击开始){
var数据=voronoi(顶点);
路径=路径
.数据(数据,多边形);
path.exit().remove();
path.enter().append(“路径”)
.attr(“类”,函数(d,i){返回“q”+(i%9)+“-9”;})
.attr(“d”,多边形);
path.order();
圆=圆。数据(顶点)
attr(“transform”,函数(d){return“translate”(+d+)”);})
circle.enter().append(“circle”)
.attr(“transform”,函数(d){return“translate”(+d+)”);})
.attr(“r”,1.5)
.attr('fill',fromClick?'white':'')
circle.exit().remove();
}
函数多边形(d){
返回d?“M”+d.join(“L”)+Z:null;
}

对不起,我是新来的,把你的名字弄错了。没问题。欢迎来到SO!