悬停在上面时显示打印线长度的注释

Display annotation of length of a plotted line when hovered over

本文关键字:注释 打印 在上面 显示 悬停      更新时间:2023-09-26

使用dygraph,我将绘制一个看起来像楼梯的系列:连续的水平线和垂直线。(宽度可变,高度不变(。

我想让一个注释或标签显示水平线悬停时的长度。如何做到这一点?也许有一种方法:

  • 提供当线段悬停在其上时调用的回调
  • 使用该回调添加一个临时注释(带有文档注释功能(

或者也许还有更好的方法?

示例:

<head><script  
    type="text/javascript" 
    src="http://dygraphs.com/dygraph-combined.js"></script>
</head>
<body>
    <div id="graphdiv"></div>
    <script type="text/javascript">
    var g = new Dygraph(document.getElementById("graphdiv"),
    [
        [0, 1],     // Starts at height 1, step width is 2
        [2, 2],     // step width is 1
        [3, 3],     // step width is 0.5
        [3.5, 4],   // step width is 0.25
        [3.75, 5],  // remainder is at height 5
    ],
    {
        stepPlot: true
    });
</script>
</body>

有关Dygraph网站上阶梯图的更多示例,请参阅此处

进度:

我关注的是在dygraph.js:findClosestPoint()的源代码中找到的一个方法。不幸的是,它在可见的画布上对点进行线性(蛮力(搜索(我认为(,但它会的。所以我需要计算:

  1. 什么叫它
  2. 我应该利用那些来电者中的哪一个
  3. 如何将回调附加到它

我认为你可以使用annotate来体面地解决这个问题(http://dygraphs.com/annotations.html)

这里有一个jsfiddle可能的解决方案:示例fiddle

基本上你添加这样的工作站:

g.setAnnotations([
    {      
      series: "seriesX",
      x: 0,
      shortText: "2"
    },
    ...

这将在第一行的开头设置一个2。。然后你可以用1表示seconf线的长度,还有另一个站,依此类推:

...
{      
   series: "seriesX",
   x: 2,
   shortText: "1"
}
...

我知道这不是当你悬停在直线上时,但我认为这是你使用dygraph时得到的最接近的结果。另一种选择是监听mousemove,并在图形上方使用div根据鼠标坐标/图形坐标正确定位,但这需要更多的代码。

编辑:好吧,我理解如果有很多点紧密地结合在一起,那看起来会很可怕。你可以在悬停时显示和隐藏注释,如下所示:更新的fiddle

我使用jQuery来选择注释,还稍微更改了文本,以便在多个点具有相同标题的情况下更容易地选择它。如果不使用jQuery,您可以通过其他方式手动进行选择。

      g.updateOptions( {
        annotationMouseOverHandler: function(annotation, point, dygraph, event)
        {       
        var anno = $(".dygraphDefaultAnnotation[title='" + annotation.text +"']");
            //alert(annotation.text);
            anno.removeClass("annotationHidden");
        },
      annotationMouseOutHandler:function(annotation, point, dygraph, event)
        {
        var anno = $(".dygraphDefaultAnnotation[title='" + annotation.text +"']");
            //alert(annotation.text);
            anno.addClass("annotationHidden");
        }
        });

还可以使用循环创建注释数组,这样就不会有太多代码。