如何将 d3.event.Y 作为 <g> 元素中的位置

how to get d3.event.Y as location in a <g> element

在 d3.js V4 中,d3.event.y 给出事件在 SVG 元素中的 y 位置,但我需要事件的位置,因为它在 G 元素中。例如,如果鼠标位于 G 元素的顶部,那么 d3.event.y 应该为零。但在我的尝试中,如果鼠标位于 SVG 元素的顶部,则它仅为零。这是我的尝试: jsbin link - 尝试上下拖动 'water' 行。水线从不匹配鼠标拖动。我的 SVG 将随页面宽度缩放,因此我无法对值进行硬编码。

D3 V4 代码:

var high = null;
d3.select('#bfG').call(
  d3.drag().on('start', function () {
    //get the real height of the <g> element
    high = this.getBoundingClientRect().height;
  }).on('drag', function () {
    // % of the location relative to the <g> height
    var p = (d3.event.y / high) * 100;
    var q = Math.max(0, Math.min(100, p));
    d3.select('#stop1').attr('offset', q + '%');
    d3.select('#stop2').attr('offset', q + '%');
  })
);

您可以使用getBBox方法获取用户space中形状的y和height属性,然后计算偏移量:

var bbox = this.getBBox()
var p = (d3.event.y - bbox.y) / bbox.height * 100

示例:1, 2

我必须说你的代码很有趣。

嗯,我准备推荐你用d3.mouse(container),那我觉得d3.mouse(container)和[=19没什么区别=]d3.event.y 在这种情况下,因为你没有变换 g 元素所以 g 元素与 svg.

共享相同的坐标系

我的意思是 d3.mouse(this)[1]d3.event.y 将产生相同的值案例.