【问题标题】:Chart JS custom tooltip option?Chart JS自定义工具提示选项?
【发布时间】:2020-07-17 16:25:58
【问题描述】:

我正在尝试使用 Chart.Js 构建图表。这个chart.js 有工具提示的默认选项,我想定制工具提示选项。有没有办法让它成为可能?

这是我的代码

 var chart = null;
barChart: function (data1, data2, data3, label) {

    var data = {
        labels: label,
        datasets: [
        {
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: data1
        },
         {
             fillColor: "rgba(151,187,205,0.5)",
             strokeColor: "rgba(151,187,205,0.8)",
             highlightFill: "rgba(151,187,205,0.75)",
             highlightStroke: "rgba(151,187,205,1)",
             data: data2
         },
          {
              fillColor: "rgba(0,255,0,0.3)",
              strokeColor: "rgba(220,220,220,0.8)",
              highlightFill: "rgba(220,220,220,0.75)",
              highlightStroke: "rgba(0,255,0,0.3)",
              data: data3
          },
        ]
    }
    var cht = document.getElementById('exampleCanvas');
    var ctx = cht.getContext('2d');
    if (chart)
        chart.destroy();
    chart = new Chart(ctx).Bar(data);
}

【问题讨论】:

    标签: javascript chart.js


    【解决方案1】:

    试试这个:

    您可以使用此代码进行全局更改:

    Chart.defaults.global = {
    
        // Boolean - Determines whether to draw tooltips on the canvas or not
        showTooltips: true,
    
        // Array - Array of string names to attach tooltip events
        tooltipEvents: ["mousemove", "touchstart", "touchmove"],
    
        // String - Tooltip background colour
        tooltipFillColor: "rgba(0,0,0,0.8)",
    
        // String - Tooltip label font declaration for the scale label
        tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
    
        // Number - Tooltip label font size in pixels
        tooltipFontSize: 14,
    
        // String - Tooltip font weight style
        tooltipFontStyle: "normal",
    
        // String - Tooltip label font colour
        tooltipFontColor: "#fff",
    
        // String - Tooltip title font declaration for the scale label
        tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
    
        // Number - Tooltip title font size in pixels
        tooltipTitleFontSize: 14,
    
        // String - Tooltip title font weight style
        tooltipTitleFontStyle: "bold",
    
        // String - Tooltip title font colour
        tooltipTitleFontColor: "#fff",
    
        // Number - pixel width of padding around tooltip text
        tooltipYPadding: 6,
    
        // Number - pixel width of padding around tooltip text
        tooltipXPadding: 6,
    
        // Number - Size of the caret on the tooltip
        tooltipCaretSize: 8,
    
        // Number - Pixel radius of the tooltip border
        tooltipCornerRadius: 6,
    
        // Number - Pixel offset from point x to tooltip edge
        tooltipXOffset: 10,
    
        // String - Template string for single tooltips
        tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
    
        // String - Template string for single tooltips
        multiTooltipTemplate: "<%= value %>",
    
        // Function - Will fire on animation progression.
        onAnimationProgress: function(){},
    
        // Function - Will fire on animation completion.
        onAnimationComplete: function(){}
    }
    

    将此Link 用作参考

    【讨论】:

    • Jake 先生,我已经阅读了这个,我在这里感到困惑,我在哪里可以编写自定义工具提示功能?。这是默认选项,我理解。
    • 如果有人知道如何为每个数据点自定义工具提示文本,我也会遇到同样的问题?
    • 谢谢! tooltipTemplate 正是我所需要的。
    【解决方案2】:

    chart.js 的新版本,第 2 版,可在此处找到:

    https://github.com/nnnick/Chart.js/releases

    第二版增加tooltip callbacks:

    每个工具提示回调(beforeTitle、title、afterTitle 等)都接受一个字符串或一个数组。如果使用数组,它将产生多行。工具提示现在还提供了更多用于视觉自定义的选项。


    但是,chart.js 有一个分支,称为 chartNew.js,可在此处找到:

    https://github.com/FVANCOP/ChartNew.js/

    它为古老的 chart.js 添加了几项重要的增强功能,包括:

    • 工具提示功能(下载/解压缩时,查看Samples 文件夹并查看annotateFunction.html。将鼠标悬停在任意点上时,您可以执行任何操作。)

    • 将颜色数组传递给条形图(而不是系列中的每个条形都具有相同的颜色)

    • 将文本放在图表上任意位置

    许多等等。


    请注意,chart.js 在版本 2 中得到了极大的增强,但新版本并不完全向后兼容(只是更改为 v2 插件破坏了我现有的代码),而 chartNew.js 将在扩展功能的同时使用旧代码。

    【讨论】:

      【解决方案3】:

      我用过这个,我在stackoverflow上找到了它,但我很难再找到它

      <div id="chartjs-tooltip"></div>
      


      var chartoptions =
      {
          customTooltips: function ( tooltip )
          {
              var tooltipEl = $( "#chartjs-tooltip" );
              if ( !tooltip )
              {
                  tooltipEl.css( {
                      opacity: 0
                  } );
                  return;
              }
      
              tooltipEl.removeClass( 'above below' );
              tooltipEl.addClass( tooltip.yAlign );
      
              // split out the label and value and make your own tooltip here
              var parts = tooltip.text.split( ":" );
              var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
              tooltipEl.html( innerHtml );
      
              tooltipEl.css( {
                  opacity: 1,
                  left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
                  top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
                  fontFamily: tooltip.fontFamily,
                  fontSize: tooltip.fontSize,
                  fontStyle: tooltip.fontStyle
              } );
          }
      }
      

      链接到我得到它的地方:Chart.js: changing tooltip template

      【讨论】:

      【解决方案4】:

      您可以检查工具提示 css - http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration

      tooltips: 
      {
      
          bodyFontColor: "#000000", //#000000
          bodyFontSize: 50,
          bodyFontStyle: "bold",
          bodyFontColor: '#FFFFFF',
          bodyFontFamily: "'Helvetica', 'Arial', sans-serif",
          footerFontSize: 50,
          callbacks: {
              label: function(tooltipItem, data) {
                      var value = data.datasets[0].data[tooltipItem.index];
                    if(tooltipItem.index == 0) {
                      return "<?php echo $data1;?>";
                      }
                  else if(tooltipItem.index == 1) {
                      return "<?php echo $data2;?>";
                  }
                  else if(tooltipItem.index == 2) {
                      return "<?php echo $data3;?>";
                  }
                  else {
                      return "<?php echo $data4; ?>";
                      }
              },
          },
      },
      

      【讨论】:

        【解决方案5】:

        当您知道将选项放在哪里时,这非常简单。

        答案是在创建图表时添加自定义选项:

        chart = new Chart(ctx).Bar(data, {"options goes here"} );
        

        在传递带有数据信息的数据变量后,您可以添加自定义选项,例如,您想要更改工具提示标题的大小,并且您还想在工具提示的标题中放置浅灰色你会做这样的事情:

            chart = new Chart(ctx).Bar(data, { 
             
              //Option for title font size in pixels
              tooltipTitleFontSize: 14, 
             
              //Option for tooltip title color
              tooltipTitleFontColor: "#eee"
            });
        

        您可以做的另一种方法是将选项集创建为用于组织目的的变量并能够重用它。

         // Create a set of relevant options for you chart  
                    
         var myoptions = { 
           scaleShowGridLines : false,     
           responsive : true, 
           scaleFontSize: 12,
           pointDotRadius : 4,
           scaleFontStyle: 14,
           scaleLabel: "<%= ' ' + value%> %",
         }  
        
        //Create the Chart
         
        chart = new Chart(ctx).Bar(data, myoptions);
        

        我希望现在很清楚

        问候

        【讨论】:

        • 可以在tooltip中写html吗?
        【解决方案6】:

        我发现这个页面很有帮助:

        https://github.com/nnnick/Chart.js/blob/master/samples/pie-customTooltips.html

        他展示了在哪里以及如何为您的自定义工具提示定义函数,以及样式示例。 我不得不修改代码以满足我的需要,但这是一个很好的例子,说明了如何实现自定义工具提示功能。

        一开始让我失望的一些注意事项:

        1) 需要修改样式规则中的 id 以匹配您的工具提示 div。 (这很明显,但我一开始没听懂)

        2) tooltip.text 将遵循您在选项中为 'tooltipTemplate' 设置的格式,或在 chart.js 中设置的默认 tooltipTemplate

        【讨论】:

        • @kmgkumar 它是 4 年前发布的
        【解决方案7】:

        也许这对你有帮助

           Chart.types.Line.extend({
           name: "LineAlt",
           initialize: function (data) {
            Chart.types.Line.prototype.initialize.apply(this, arguments);
            var xLabels = this.scale.xLabels
            xLabels.forEach(function (label, i) {
                if (i % 2 == 1)
                    xLabels[i] = label.substring(1, 4);
              })
           }
         });
        
        var data = {
        labels: ["1/jan/08", "15/fab/08", "1/mar/08", "1/apr/08", "10/apr/08", "10/may/2008", "1/jun/2008"],
        datasets: [{
            label: "First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,20,20,1)",
            pointColor: "rgba(220,20,20,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 90]
        }, {
            label: "Third dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(15,187,25,1)",
            pointColor: "rgba(15,187,25,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [38, 55, 50, 65, 35, 67, 54]
        }]
        

        };

        var ctx = document.getElementById("myChart").getContext("2d");
        
        var myChart = new Chart(ctx).LineAlt(data);
        
        
        // Chart.js replaces the base inRange function for Line points with a          function that checks only the x coordinate
        // we replace it with the original inRange fucntion (one that checks both x and y coordinates)
        
         myChart.datasets.forEach(function(dataset) {
          dataset.points.forEach(function(point) {
            point.inRange = Chart.Point.prototype.inRange;
          });
        });
        
        // Chart.js shows a multiTooltip based on the index if it detects that there are more than one datasets
        // we override it to show a single tooltip for the inRange element
        
        myChart.showTooltip = function(ChartElements, forceRedraw) {
          // this clears out the existing canvas - the actual Chart.js library code is a bit more optimized with checks for whether active points have changed, etc.
          this.draw();
          // draw tooltip for active elements (if there is one)
          Chart.helpers.each(ChartElements, function(Element) {
            var tooltipPosition = Element.tooltipPosition();
            new Chart.Tooltip({
              x: Math.round(tooltipPosition.x),
              y: Math.round(tooltipPosition.y),
              xPadding: this.options.tooltipXPadding,
              yPadding: this.options.tooltipYPadding,
              fillColor: this.options.tooltipFillColor,
              textColor: this.options.tooltipFontColor,
              fontFamily: this.options.tooltipFontFamily,
              fontStyle: this.options.tooltipFontStyle,
              fontSize: this.options.tooltipFontSize,
              caretHeight: this.options.tooltipCaretSize,
              cornerRadius: this.options.tooltipCornerRadius,
              text: Chart.helpers.template(this.options.tooltipTemplate, Element),
              chart: this.chart,
              custom: this.options.customTooltips
            }).draw();
          }, this);
        };
        

        http://jsfiddle.net/6cgo4opg/747/

        【讨论】:

          猜你喜欢
          • 2022-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-09
          • 2020-11-26
          • 1970-01-01
          • 2013-06-23
          • 2011-09-28
          • 1970-01-01
          相关资源
          最近更新 更多