2016-04-04 71 views
0

我如何到達ChartJS只返回圖上點(在鼠標上)的值而不是整個數據集?圖表JS - 單行(點)工具提示

<table> 
<tr> 
<td> 
    <div style="width:30%"> 
     <div> 
      <canvas id="canvas" height="600" width="1000"></canvas> 

     </div> 
    </div> 
    </td> 
    <td style="text-align:center;"><div id="placeholder" height="450" width="600"></div> 

<script> 
    var lineChartData = { 
     labels : [<?php echo $_SESSION['GRAFICO2']; ?>], 
     datasets : [<?php echo $_SESSION[$_GET['vGrafico']]; ?> 

     ] 

    } 


window.onload = function(){ 
    var ctx = document.getElementById("canvas").getContext("2d"); 
    window.myLine = new Chart(ctx).Line(lineChartData, {bezierCurve: false, pointDot : true, datasetStroke : true, showTooltips: true, pointHitDetectionRadius : 2, offsetGridLines : true, TooltipTemplate: "<%= label %> - <%= data %>"}); 
    legend(document.getElementById('placeholder'), lineChartData); 
} 

</script> 

像這樣 now - than

回答

0

爲此,您可以通過覆蓋圖表的showTooltip和分inRange方法。

預覽

enter image description here


腳本

... 
var myChart = new Chart(ctx).Line(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); 
} 

最明顯的缺點是,如果有2個(或以上)的點併攏,你會看到可能有可能重疊的多個工具提示。


小提琴 - http://jsfiddle.net/v7mtz64o/