2017-08-09 159 views
0

我使用Chart.js 2.x折線圖來創建時間軸事件圖表。Chart JS 2.x:如何在時間軸圖表中顯示工具提示?

它運行良好,但我無法弄清楚當鼠標移過一條線時如何顯示工具提示。我想要顯示的信息與標籤中顯示的相同(在「標籤A」,「標籤B」或「標籤C」下面的示例中)我嘗試添加工具提示選項enabled = truemode = label,但它不起作用。

這是我JSFiddle

這裏是我的代碼:

HTML

<div style="height: 250px;"> 
<canvas id="timeline"></canvas> 
</div> 

的Javascript

var ctx = $("#timeline").get(0).getContext("2d"); 

var data = { 
    labels: ['Red','Blue','Yellow'], 
    datasets: [ 
    { 
     label: 'Label A', 
     backgroundColor: "rgba(208,255,154,1)", 
     borderColor: "rgba(208,255,154,1)", 
     fill: false, 
     borderWidth : 15, 
     pointRadius : 0, 
     data: [ 
     { 
      x: new Date(2014,01,01), 
      y: 3              
     }, { 
      x: new Date(2017,10,01), 
      y: 3              
     } 
     ] 
    }, 
    { 
     label: 'Label B', 
     backgroundColor: "rgba(208,255,154,1)", 
     borderColor: "rgba(208,255,154,1)", 
     fill: false, 
     borderWidth : 15, 
     pointRadius : 0, 
     data: [ 
     { 
      x: new Date(2009,01,01), 
      y: 2              
     }, { 
      x: new Date(2012,09,01), 
      y: 2              
     } 
     ] 
    }, 
    { 
     label: 'Label C', 
     backgroundColor: "rgba(246,156,85,1)", 
     borderColor: "rgba(246,156,85,1)", 
     fill: false, 
     borderWidth : 15, 
     pointRadius : 0, 
     data: [ 
     { 
      x: new Date(2017,01,01), 
      y: 1              
     }, { 
      x: new Date(2017,08,01), 
      y: 1              
     } 
     ] 
    }, 
    ] 
}; 

var options = { 
    maintainAspectRatio: false, 
    legend : { 
    display : true 
    }, 
    scales: { 
    xAxes: [{ 
     type: 'time', 
     unit: 'month', 
     unitStepSize: 1, 
     time: { 
     displayFormats: { 
      'month': 'MM/YY', 
      'quarter': 'MM/YY' 
     } 
     }, 
     position: 'bottom', 
     ticks : { 
     beginAtzero :true 
     }}, 
      { 
       type: 'time', 
       unit: 'month', 
       unitStepSize: 1, 
       time: { 
       displayFormats: { 
        'month': 'MM/YY', 
        'quarter': 'MM/YY' 
       } 
       }, 
       position: 'top', 
       ticks : { 
       beginAtzero :true 
       } 
      }], 
    yAxes : [{ 
     display: false, 
     scaleLabel : { 
     display : false 
     }, 
     ticks : { 
     beginAtZero :true, 
     max : 5 
     } 
    }] 
    }, 
    tooltips: { 
    enabled: true, 
    mode: 'label', 
    }, 
}; 

var scatterChart = new Chart(ctx, { 
    type: 'line', 
    data: data, 
    options: options 
}); 
+0

我認爲你需要這個 - https://stackoverflow.com/questions/17064913/顯示工具提示功能於帆布圖表 –

回答

0

我不得不把intersect: false屬性添加到工具提示

Updated JSFiddle

工具提示代碼:

tooltips: { 
    enabled: true, 
    intersect: false, 
    titleFontSize: 0, 
    callbacks: { 
     label: function(tooltipItems, data) { 
     return data.datasets[tooltipItems.datasetIndex].label || 'Other'; 
     }, 
    } 
    } 
相關問題