首页 > 解决方案 > 缩放交互后如何向面积图添加工具提示

问题描述

我正在 D3 中创建一个面积图,其中包括两个主要功能:

1) 一个时间滑块,用于更改 x 轴上的日期范围并更新图表(类似于刷子缩放)

2) 悬停时出现的工具提示,以显示给定日期的确切值

这两个功能在图表加载时起作用,但是当我通过拖动幻灯片来更改 x 轴范围时,我遇到了一个问题:面积图通过放大新的轴和区域进行转换,但是当我悬停显示工具提示、工具提示位置和值与行/区域的新路径不匹配。

我尝试将创建工具提示对象(附加到focusvar)的所有代码包装在一个函数中,然后在移动滑块时调用该函数。我还尝试将 x 比例存储在一个变量中,该变量在时间滑块移动时更新,并将其传递给drawFocus()函数。工具提示仍然出现在原始位置。

使用时间滑块缩放后工具提示出现位置的屏幕截图

将链接粘贴到 bl.ock 以获取下面的完整代码,但我认为问题来自tipMove()函数中的某些内容,每当用户将鼠标悬停在图表上时都会调用该函数。(current_x 存储时间滑块定义的 x 比例):

// function that adds tooltip on hover
                function tipMove() {

                    // below code finds the date by bisecting and
                    // stores the x and y coordinate as variables
                    let x0 = current_x.invert(d3.mouse(this)[0]);
                    let i = bisectDate(data, x0, 1);
                    let d0 = data[i - 1];
                    let d1 = data[i];
                    let d = x0 - d0.date > d1.date - x0 ? d1 : d0;

                    // place the focus objects on the same path as the line
                    focus.attr('transform', `translate(${current_x(d.date)}, ${y(d.value)})`);

                    // position the x line
                    focus.select('line.x')
                        .attr('x1', 0)
                        .attr('x2', x(d.date))
                        .attr('y1', 0)
                        .attr('y2', 0);

                    // console.log(x0)

                    // position the y line
                    focus.select('line.y')
                        .attr('x1', 0)
                        .attr('x2', 0)
                        .attr('y1', 0)
                        .attr('y2', height - y(d.value));

                    // position the text
                    focus.select('text').text(d.value).transition() // slowly fade in the tooltip
                        .duration(100)
                        .style("opacity", 1);

                    // show the circle on the path
                    focus.selectAll('.focus circle')
                        .style("opacity", 1)

};

完整代码在这里:https ://blockbuilder.org/bendoesdata/99c2ca152f760b6d93c923ee9462f4fa

我希望工具提示在图表放大后跟随线条,而是工具提示跟随线条的原始路径(在剪辑路径中不再可见)。

标签: javascriptd3.js

解决方案


推荐阅读