d3.js v4,如何在鼠标悬停时有一条线跟随鼠标,同时也有一个圆圈跟随路径?

2024-01-27

这是我的 js 小提琴:https://jsfiddle.net/DerNalia/3wzLv9yg/1/ https://jsfiddle.net/DerNalia/3wzLv9yg/1/

我一直在尝试从这里解释代码:带有鼠标悬停工具提示的多系列折线图 https://stackoverflow.com/questions/34886070/d3-js-multiseries-line-chart-with-mouseover-tooltip/34887578#34887578,但我似乎无法让它发挥作用。

这就是我到目前为止所拥有的——几乎是复制粘贴。

// append a g for all the mouse over nonsense
var mouseG = svg.append("g")
  .attr("class", "mouse-over-effects");

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

// keep a reference to all our lines
var lines = document.getElementsByClassName('line');

// here's a g for each circle and text on the line
var mousePerLine = mouseG.selectAll('.mouse-per-line')
  .data(data)
  .enter()
  .append("g")
  .attr("class", "mouse-per-line");

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

// the text
mousePerLine.append("text")
  .attr("transform", "translate(10,3)");

// rect to capture mouse movements
mouseG.append('svg:rect')
  .attr('width', width)
  .attr('height', height)
  .attr('fill', 'none')
  .attr('pointer-events', 'all')
  .on('mouseout', function() { // on mouse out hide line, circles and text
    d3.select(".mouse-line")
      .style("opacity", "0");
    d3.selectAll(".mouse-per-line circle")
      .style("opacity", "0");
    d3.selectAll(".mouse-per-line text")
      .style("opacity", "0");
  })
  .on('mouseover', function() { // on mouse in show line, circles and text
    d3.select(".mouse-line")
      .style("opacity", "1");
    d3.selectAll(".mouse-per-line circle")
      .style("opacity", "1");
    d3.selectAll(".mouse-per-line text")
      .style("opacity", "1");
  })
  .on('mousemove', function() { // mouse moving over canvas
    var mouse = d3.mouse(this);

    // move the vertical line
    d3.select(".mouse-line")
      .attr("d", function() {
        var d = "M" + mouse[0] + "," + height;
        d += " " + mouse[0] + "," + 0;
        return d;
      });

    // position the circle and text
    d3.selectAll(".mouse-per-line")
      .attr("transform", function(d, i) {

        console.log(width/mouse[0])
        console.log(mouse[1]);
        var xDate = x.invert(mouse[0]),
            bisect = d3.bisector(function(d) { return d.x; }).right;
            idx = bisect(d.values, xDate);

        // since we are use curve fitting we can't relay on finding the points like I had done in my last answer
        // this conducts a search using some SVG path functions
        // to find the correct position on the line
        // from http://bl.ocks.org/duopixel/3824661
        var beginning = 0,
            end = lines[i].getTotalLength(),
            target = null;

        while (true){
          target = Math.floor((beginning + end) / 2);
          pos = lines[i].getPointAtLength(target);
          if ((target === end || target === beginning) && pos.x !== mouse[0]) {
              break;
          }
          if (pos.x > mouse[0])      end = target;
          else if (pos.x < mouse[0]) beginning = target;
          else break; //position found
        }

        // update the text with y value
        //d3.select(this).select('text')
        //  .text(y.invert(pos.y).toFixed(2));

              d3.select(this).select('circle')
              .attr('cy', pos.x)
              .attr('cx', pos.y);

        // return position
        return "translate(" + mouse[0] + "," + pos.y +")";
      });
  });

如果小提琴出现问题,这是我目前所拥有的:

And here is how I would like it to appear (pardon horrible paint skills): enter image description here

我的问题也可能与我的错误有关。无法读取未定义的属性“长度”。


更新的小提琴:https://jsfiddle.net/3wzLv9yg/2/ https://jsfiddle.net/3wzLv9yg/2/。有一些事情出了问题:

线圈

var mousePerLine = mouseG.selectAll('.mouse-per-line')
  .data(data)
  .enter()
  .append("g")
  .attr("class", "mouse-per-line");

该声明增加了一个新的g每个元素数据点,而不是每行。将其替换为一个长度为行数的数组,以获取每行的一个元素。例如替换.data(data) with .data(d3.range(lines.length)).

圆定位的多种技巧

看起来您已经结合了两种不同的技术来计算圆的 y 位置,一种涉及根据数据值进行计算,另一种涉及根据 svg 元素进行计算。

根据数据值计算的代码具有以下几行:

var xDate = x.invert(mouse[0]),
    bisect = d3.bisector(function(d) { return d.x; }).right;
    idx = bisect(d.values, xDate);

有一个错误bisect(d.values, xDate); as d.values没有分配到任何地方。它应该是bisect(data, xDate);,但它可能是无关紧要的,因为它没有在其他地方使用,因为函数的其余部分根据 svg 路径计算 y 位置。如果您使用这种方法,您可以摆脱 bisect 和 idx:

var xDate = x.invert(mouse[0]);

设置位置

这应该可以缓解控制台错误,但鼠标圆圈仍然无法正确跟踪。这是因为圆的位置设置了两次:

d3.select(this).select('circle')
  .attr('cy', pos.x)
  .attr('cx', pos.y);

// return position
return "translate(" + mouse[0] + "," + pos.y +")";

这些语句集g元素到正确的位置,但它也设置circle到等量的偏移量。你只需要一个。由于当前的实施设置了transform of the g元素,保留该元素并消除圆偏移可能更容易。

// return position
return "translate(" + mouse[0] + "," + pos.y +")";

所有的改变都在这里:https://jsfiddle.net/3wzLv9yg/2/ https://jsfiddle.net/3wzLv9yg/2/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

d3.js v4,如何在鼠标悬停时有一条线跟随鼠标,同时也有一个圆圈跟随路径? 的相关文章

随机推荐