chart.js 的水平线插件出现意外标识符错误

Unexpected identifier error with horizontal line plugin for chart.js

我正在尝试绘制条形图并在条形图上的 y=1 和 y=3 处显示一些水平线。论坛上有人建议使用插件来执行此操作,但是当我尝试时(如图所示:https://jsfiddle.net/prbo0f2y/7/),控制台一直提示 unexpected identifier。有谁知道错误在哪里?我使用的是chart.js(2.5版)和Bootstrap 3.错误似乎指向这部分代码:

options: {
    "horizontalLine": [{
        "y": 3,
        "style": "rgba(255, 0, 0, .4)",
        "text": "max"
    }, {
        "y": 1,
        "text": "min"
    }]
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

点击此处:

然后它会告诉你错误的确切位置:

…用淡黄色突出显示向您显示从 scales:.

开始的行

您需要在对象文字中的每个 key:value 对之间放置一个逗号。

您的 options 配置中 horizontalLinescales 之间似乎存在语法错误(例如缺少逗号)。

话虽如此,我建议您改用 chartjs-plugin-annotation 插件来执行此操作。这是 created/supported 由创建 chart.js 的同一个人开发的插件,除了绘制线条外,它还提供更多功能,以备您日后需要。

这里是水平线配置示例。

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February"],
    datasets: [{
      label: 'Dataset 1',
      borderColor: window.chartColors.blue,
      borderWidth: 2,
      fill: false,
      data: [2, 10]
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Drsw Line on Chart'
    },
    tooltips: {
      mode: 'index',
      intersect: true
    },
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        scaleID: 'y-axis-0',
        value: 5,
        borderColor: 'rgb(75, 192, 192)',
        borderWidth: 4,
        label: {
          enabled: false,
          content: 'Test label'
        }
      }]
    }
  }
});

您还可以查看演示上述内容的codepen example