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

使用Chart.js绘制卡丁车车手圈速图表的技术实现疑问

用Chart.js实现车手圈速横向条形图解决方案

数据预处理:毫秒转可读时间格式

你的圈速数据是毫秒单位,直接展示不够直观,先写个转换函数把毫秒转成 mm:ss.sss 格式:

function formatLapTime(ms) {
  const minutes = Math.floor(ms / 60000);
  const seconds = Math.floor((ms % 60000) / 1000);
  const milliseconds = ms % 1000;
  // 补零格式化
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
}

完整Chart.js实现代码

下面是适配你数据集的横向条形图实现,直接复制就能用:

<!-- 引入Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- 图表容器 -->
<div style="width: 80%; margin: 0 auto;">
  <canvas id="lapTimeChart"></canvas>
</div>

<script>
// 你的原始数据集
const lapData = [
  {'Driver': 'JAN', 'LapTime': 97379},
  {'Driver': 'PED', 'LapTime': 93996},
  // 更多数据...
];

// 毫秒转时间格式函数
function formatLapTime(ms) {
  const minutes = Math.floor(ms / 60000);
  const seconds = Math.floor((ms % 60000) / 1000);
  const milliseconds = ms % 1000;
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
}

// 提取图表所需的标签和数据
const labels = lapData.map(item => item.Driver);
const lapTimes = lapData.map(item => item.LapTime);

// 初始化图表
const ctx = document.getElementById('lapTimeChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: '圈速',
      data: lapTimes,
      backgroundColor: 'rgba(54, 162, 235, 0.6)',
      borderColor: 'rgba(54, 162, 235, 1)',
      borderWidth: 1
    }]
  },
  options: {
    indexAxis: 'y', // 设置为横向条形图
    scales: {
      x: {
        title: {
          display: true,
          text: '圈速 (mm:ss.sss)'
        },
        // 自定义x轴刻度标签为时间格式
        ticks: {
          callback: function(value) {
            return formatLapTime(value);
          }
        }
      },
      y: {
        title: {
          display: true,
          text: '车手'
        }
      }
    },
    plugins: {
      tooltip: {
        // 鼠标悬浮时显示格式化后的时间
        callbacks: {
          label: function(context) {
            return `圈速: ${formatLapTime(context.raw)}`;
          }
        }
      }
    }
  }
});
</script>

关键说明

  • 设置 indexAxis: 'y' 把条形图转为横向,匹配你期望的图表样式
  • 通过ticks.callback和tooltip.callbacks.label两处自定义,让图表的刻度和悬浮提示都显示可读的时间格式
  • 保留原始毫秒数值作为图表数据,确保条形长度的准确性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:55:12