Chart.register不是函数报错:Chart.js柱状图数据标签显示异常求助
问题解决:Chart.register 不是函数 + 柱状图数据标签显示
错误原因
你使用的是Chart.js 2.8.0,但Chart.register()是Chart.js 3.x及以上版本才新增的API,2.x版本不支持该方法。同时你引入的chartjs-plugin-datalabels@2.0.0-rc是适配Chart.js 3.x的版本,和2.8.0完全不兼容,这就是报错的核心原因。
下面提供两种可行的解决方案:
方案1:升级Chart.js到3.x版本(推荐,插件功能更完善)
- 替换Chart.js和插件的CDN为适配3.x的版本:
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0"></script>
- 调整Chart.js 3.x的配置语法(3.x对配置结构做了重构,比如坐标轴、图例、标题的位置变化):
var chartOptionsWeekly = { responsive: true, plugins: { datalabels: { anchor: 'end', align: 'end', color: 'white' // 简化配置,直接设置颜色即可 }, legend: { position: "top", labels: { color: "white" } }, title: { display: false, text: "Daily Trend" } }, scales: { y: { // 2.x的yAxes改为y beginAtZero: true, ticks: { color: 'white', fontSize: 14, stepSize: 20 }, title: { // 2.x的scaleLabel改为title display: true, text: 'Attendance Percentage', color: 'white' } }, x: { // 2.x的xAxes改为x ticks: { color: 'white', fontSize: 14 }, title: { display: true, text: 'Last 7 Days', color: 'white' } } } } // 3.x支持Chart.register注册插件 Chart.register(ChartDataLabels) window.onload = function () { var ctxDaily = document.getElementById("barChartWeekly").getContext("2d"); window.myBar = new Chart(ctxDaily, { type: "bar", data: barChartDataWeekly, options: chartOptionsWeekly }); };
方案2:保留Chart.js 2.8.0,降级插件到适配2.x的版本
- 替换插件CDN为适配2.x的1.x版本:
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@1.0.0"></script>
- 修改插件注册方式(2.x用
Chart.plugins.register,而非Chart.register),并调整配置:
var chartOptionsWeekly = { responsive: true, plugins: { datalabels: { anchor: 'end', align: 'end', color: 'white' // 2.x版本的插件配置更简洁 } }, legend: { position: "top", labels: { fontColor: "white" } }, title: { display: false, text: "Daily Trend" }, scales: { yAxes: [{ ticks: { beginAtZero: true, fontColor: 'white', fontSize: 14, stepSize: 20 }, scaleLabel: { display: true, labelString: 'Attendance Percentage', fontColor: 'white' } }], xAxes: [{ ticks: { beginAtZero: true, fontColor: 'white', fontSize: 14 }, scaleLabel: { display: true, labelString: 'Last 7 Days', fontColor: 'white' } }] } } // 2.x版本用Chart.plugins.register注册全局插件 Chart.plugins.register(ChartDataLabels); window.onload = function () { var ctxDaily = document.getElementById("barChartWeekly").getContext("2d"); window.myBar = new Chart(ctxDaily, { type: "bar", data: barChartDataWeekly, options: chartOptionsWeekly }); };
两种方案都能解决Chart.register is not a function的错误,同时实现柱状图顶部显示数据标签的需求。
内容的提问来源于stack exchange,提问作者Teena
相关产品推荐
相关产品推荐

