javascript - 如何让一条线跟随鼠标悬停,同时放大图表?

标签 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?

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

  • 移动鼠标时线条闪烁或淡出
  • 缩放功能不适用于鼠标滚轮(仅当使用鼠标滚轮时才有效) 鼠标在移动)

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

我尝试不在 mouseG 元素中创建一条线(如示例所示),而是在我自己的 zoom 元素上创建一条线。该行根本不再显示。

这是我的 fiddle https://jsfiddle.net/zkdxrtuc/8/

最佳答案

line组放在zoomrect下方。

将第二个鼠标事件处理程序添加到 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
  });

关于javascript - 如何让一条线跟随鼠标悬停,同时放大图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53595181/

相关文章:

javascript - 我可以使用 AJAX 'POST' 将数据发布到服务器上的 JSON 文件吗?

javascript - 我可以引用变量上的单击事件吗?

javascript - 使用 d3.mouse 事件作为工具提示的面积图的 d3js Angular Directive(指令)

javascript - 如何将 jquery 库和 js 文件加载到 WordPress 主题中?

javascript - Jquery:如何使用现有的输入文本值而不使用像 "change", "keyup"这样的交互

php - 两条验证消息都出现在 javascript 和 php 上

javascript - 关联数组并使用父级 d 作为 Selection.data() 的源数组

javascript - 如何在 D3.js SVG 网格矩形上居中文本?

javascript - 使用D3.json调用两组json

javascript - d3js : Add quantitative dimension to Hierarchical Edge Bundling