d3计算点

时间:2018-08-25 18:12:16

标签: javascript html d3.js svg

我有这个椭圆的基本图形:https://codepen.io/almn22/pen/zJrWrd

我正在尝试做到这一点,以便当您将鼠标悬停在某个区域上时,下面将显示文本输出,以显示该点有多少个形状。因此,在下面的示例中,当您将鼠标悬停在最暗的灰色区域上时,文字显示应为“ 3”。

对于我的实际用例,形状是随机的,没有可预测的形式,因此我不能指望它们是椭圆形还是圆形。我正在使用d3js将它们绘制为svg多边形。我拥有的多边形数据就是“点”属性。

任何帮助将不胜感激!

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
    ellipse {
  stroke: white;
  fill: lightgray;
  mix-blend-mode: multiply;
}
  </style>
</head>

<body>
  <script>
    const svgContainer = d3.select("body")
  		.append("svg")
  		.attr("width","560")
  		.attr("height","900").attr("translate", "45, 45");

    const ellipses = [
  		{"cx":  145, "cy":  125, "rx": 88, "ry": 20},
  		{"cx":  175, "cy":  175, "rx": 88, "ry": 77},
  		{"cx": 225, "cy": 125, "rx": 88, "ry": 55},
  		{"cx": 275, "cy": 275, "rx": 88, "ry": 77}
		];

    const svgEllipses = svgContainer
  		.selectAll("ellipse")
  		.data(ellipses)
  		.enter()
  		.append("ellipse");

    svgEllipses
    	.attr("cx", (d,i) => { return d.cx; })
    	.attr("cy", (d,i) => { return d.cy; })
    	.attr("rx", (d,i) => { return d.rx; })
    	.attr("ry", (d,i) => { return d.ry; });
    

  </script>
</body>

1 个答案:

答案 0 :(得分:0)

这是我对这个问题的解决方案。

主要思想是,单击时所有形状均对鼠标不敏感。同样,计数器n从0开始。然后,每个形状都对鼠标敏感。如果鼠标在形状内,则计数器n将增加1:n++

希望对您有帮助。

let m = {};// mouse
let shapes = Array.from(document.querySelectorAll(".shape"));

svg.addEventListener("click", e => {  
  let n = 0;// a counter
  m = oMousePos(e);// thr mouse position on click
  shapes.map(s=>{
  // all the shapes are insensitive to the mouse
  shapes.map(_s=>{_s.style.pointerEvents = "none";})
  // this shape is the only one sensitive to the mouse in this moment
  s.style.pointerEvents = "all";
  // detecting if the mouse is inside the shape
  let elmt = document.elementFromPoint(m.x, m.y);
  // if it is and the element has className.baseVal == "shape"
  if(elmt.className.baseVal == "shape"){
    //increase tho counter
    n++
  };
});
  //use the counter
  console.log(n);
});

function oMousePos(evt) {
  return {
    x: evt.clientX,
    y: evt.clientY
  };
}
svg {
  border: 1px solid;
  display: block;
  margin: 0 auto;
}

.shape {
  mix-blend-mode: multiply;
}
<svg id="svg" width="500" height="400" translate="45, 45">
  <ellipse class="shape" cx="145" cy="125" rx="88" ry="20" fill="#aaa"></ellipse>
  <circle class="shape" cx="175" cy="175" r="88" fill="#bbb"></circle>
  <ellipse class="shape" cx="225" cy="125" rx="88" ry="55" fill="#ccc"></ellipse>
  <circle class="shape" cx="275" cy="275" r="77" fill="#ddd"></circle>
</svg>