You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chart.js图表正常但Tooltip不显示,请求排查问题

解决Chart.js折线图Tooltip不显示的问题

嘿,我帮你排查了下代码,问题出在数据集的颜色配置上,还有几个小冗余点,调整后就能正常显示Tooltip啦:

问题根源

你使用的是Chart.js 2.4.0版本,当前代码里的两个数据集都把backgroundColor和borderColor设成了空数组[]。在这个版本的Chart.js中,Tooltip的渲染依赖数据集的颜色配置,空数组会导致Tooltip无法被正确触发和显示。另外第二个数据集里的type: 'line'属于冗余配置,因为整个图表已经指定了类型为折线图,去掉也不影响。

修正后的完整代码

<div style="width: 1000px; height: 600"> 
  <canvas id="myChart"></canvas> 
</div> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> 
<script> 
var ctx = document.getElementById("myChart").getContext('2d'); 
var myNewChart = new Chart(ctx, { 
  type: 'line', 
  data: { 
    labels: ["24.5.2018. 15:23:48", "24.5.2018. 16:00:00", "24.5.2018. 17:00:00"], 
    datasets: [{ 
      label: '# Temperature', 
      fill: false, 
      data: [29, 25, 24], 
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255, 99, 132, 1)',
      borderWidth: 1 
    }, { 
      label: '# Humidity', 
      data: [54, 62, 64], 
      backgroundColor: 'rgba(54, 162, 235, 0.2)',
      borderColor: 'rgba(54, 162, 235, 1)',
      borderWidth: 1, 
      fill: false 
    }] 
  }, 
  options: { 
    legend: { 
      display: true, 
      position: 'top', 
      labels: { 
        boxWidth: 80, 
        fontColor: 'rgb(60, 180, 100)' 
      } 
    }, 
    tooltips: { 
      cornerRadius: 4, 
      caretSize: 4, 
      xPadding: 16, 
      yPadding: 10, 
      backgroundColor: 'rgba(0, 150, 100, 0.9)', 
      titleFontStyle: 'normal', 
      titleMarginBottom: 15 
    } 
  } 
}); 
</script>

修改说明

  • 给每个数据集添加了具体的backgroundColor和borderColor值(你可以根据需求替换成自己想要的颜色)
  • 移除了第二个数据集中冗余的type: 'line'配置
  • 清理了数据里多余的逗号(虽然不影响,但让代码更整洁)

这样调整后,Tooltip应该就能正常显示啦,你可以试试~

内容的提问来源于stack exchange,提问作者SickWorm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:54:46