D3 JS点击多边形

时间:2016-10-12 21:54:24

标签: 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("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";
}

如何使用CLICK&添加新的Polygon同时画一个中心点?

1 个答案:

答案 0 :(得分:2)

你有个好的开始。除了mousemove上的svg侦听器之外,您还需要一个click侦听器。有了这个,你可以在每次用户点击时添加一个新的顶点。我通过在重绘函数中添加一个变量来区分由点击触发的重绘。你或许可以找到一种更清洁的方法,但希望这会有所帮助!

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(); })
    .on('click', function() { 
    	vertices.push(d3.mouse(this)); 
      redraw(true); 
     });


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

var circle = svg.selectAll("circle");

redraw();

function redraw(fromClick) {
  var data = voronoi(vertices);
  path = path
      .data(data, polygon);
  path.exit().remove();
  path.enter().append("path")
      .attr("class", function(d, i) { return "q" + (i % 9) + "-9"; })
      .attr("d", polygon);
  path.order();
  
  circle = circle.data(vertices)
  circle.attr("transform", function(d) { return "translate(" + d + ")"; })
  circle.enter().append("circle")
    .attr("transform", function(d) { return "translate(" + d + ")"; })
    .attr("r", 1.5)
    .attr('fill', fromClick ? 'white' : '')
  
  circle.exit().remove();
  
}
function polygon(d) {
  return d ? "M" + d.join("L") + "Z" : null;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>