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

Nul*_*uli 3 javascript d3.js

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

我一直试图从这里解释代码:Multiseries line chart with mouseover tooltip,但我似乎无法让它工作。

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

// 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 +")";
      });
  });
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

这是我希望它出现的方式(请原谅可怕的绘画技巧): 在此处输入图片说明

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

Ste*_*eve 6

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

线圈

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

此语句g为每个数据点而不是每行添加一个新元素。将其替换为具有行数长度的数组,以获取每行一个元素。例如替换.data(data).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);
Run Code Online (Sandbox Code Playgroud)

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

var xDate = x.invert(mouse[0]);
Run Code Online (Sandbox Code Playgroud)

设置位置

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

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

// return position
return "translate(" + mouse[0] + "," + pos.y +")";
Run Code Online (Sandbox Code Playgroud)

这些语句将g元素设置到正确的位置,但也将 设置为circle等量的偏移量。你只需要一个。由于当前的实现设置了元素的 ,因此保留transformg元素并去除圆偏移量可能更容易。

// return position
return "translate(" + mouse[0] + "," + pos.y +")";
Run Code Online (Sandbox Code Playgroud)

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