我如何在鼠标悬停时有一条线跟随鼠标,但又有放大图表?

时间:2018-12-03 13:46:58

标签: javascript d3.js

我有一个放大的图表。我想添加一条垂直线,将沿着鼠标沿图形移动,并在图形的所有线的点处显示值。 找到了一个示例d3.js v4, how do I have a line follow the mouse on hover, but also have a circle follow the path?

但是当与我的图表结合时,会出现以下问题:

  • 移动鼠标时线条闪烁或褪色
  • 缩放不适用于鼠标滚轮(仅当 鼠标在运动中)

我知道问题可能在于当光标移动时,它会拉线,并为mouseleave元素调用zoom事件。 我试图将线向左或向右移动几个像素,但这不是我想要的,并且仍然无法正常工作。

我尝试不在示例中的mouseG元素中创建一行,而是在自己的zoom元素中创建一行。该行不再显示。

这是我的小提琴https://jsfiddle.net/zkdxrtuc/8/

1 个答案:

答案 0 :(得分:1)

line组放在zoom rect下面。

将第二个鼠标事件处理程序添加到zoom rect

要显示设置为1的线,将设置为0的线隐藏。

var mouseG = svg.append("g")
      .attr("class", "mouse-over-effects");

svg.append("rect")
      .attr("class", "zoom")
      .attr("width", width)
      .attr("height", height)
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .attr('pointer-events', 'all')
      .call(zoom);

function brushed() {
//...
}

function zoomed() {
//...
}

mouseG.append("path") // this is the black vertical line to follow mouse
      .attr("class", "mouse-line")
      .style("stroke", "black")
      .style("stroke-width", "1px")
      .style("opacity", "0");

// var lines = focus.selectAll('path');

// var mousePerLine = mouseG.selectAll('.mouse-per-line')
//       .data(d3.range(lines.length))
//       .enter()
//       .append("g")
//       .attr("class", "mouse-per-line")
//       .attr('pointer-events', 'none');

// // the circle
// mousePerLine.append("circle")
//   .attr("r", 7)
//   .style("stroke", function(d) { return 'red'; })
//   .style("fill", "none")
//   .style("stroke-width", "1px")
//   .style("opacity", "0");

function showLine(){
  d3.select(".mouse-line").style("opacity", "1");
}
function hideLine(){
  d3.select(".mouse-line").style("opacity", "0");
}

svg.select(".zoom")
  .on('mouseenter.line', showLine)
  .on('mouseleave.line', hideLine)
  .on('mousemove.line', function() { // mouse moving over canvas
    var mouse = d3.mouse(this);
    //showLine();
    // move the vertical line
    d3.select(".mouse-line")
      .attr("d", function() {
        var d = "M" + (mouse[0] + margin.left) + "," + (height + margin.top);
        d += " " + (mouse[0] + margin.left) + "," + margin.top;
        return d;
      });
    // position the circle and text
  });