Javascript 如何使鼠标悬停时有一条直线跟随,同时也有图表放大?

Javascript 如何使鼠标悬停时有一条直线跟随,同时也有图表放大?,javascript,d3.js,Javascript,D3.js,我有一张缩放图表。我想添加一条垂直线,沿着图形沿鼠标移动,并显示图形中所有线的点处的值。 找到了一个例子 但当结合我的图表时,会出现以下问题: 移动鼠标时,线条会闪烁或褪色 缩放不适用于鼠标滚轮(仅当 (鼠标正在移动) 我知道问题很可能是当光标移动时,它会拉一条线,对于zoom元素称为mouseleave事件。 我试图将线条向左或向右移动几个像素,但这不是我想要的,它仍然无法正常工作 我尝试在mouseG元素中创建一行,而不是在示例中,而是在我自己的zoom元素中创建一行。该行不再显示 这是

我有一张缩放图表。我想添加一条垂直线,沿着图形沿鼠标移动,并显示图形中所有线的点处的值。 找到了一个例子

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

  • 移动鼠标时,线条会闪烁或褪色
  • 缩放不适用于鼠标滚轮(仅当 (鼠标正在移动)
我知道问题很可能是当光标移动时,它会拉一条线,对于
zoom
元素称为
mouseleave
事件。 我试图将线条向左或向右移动几个像素,但这不是我想要的,它仍然无法正常工作

我尝试在
mouseG
元素中创建一行,而不是在示例中,而是在我自己的
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
  });

所有轴也包含
路径
元素。将
组置于
缩放
下方,并更改方法以设置不透明度。下面是一个工作示例