Chart.js 3.5版本中使用Chart.register注册beforeDraw插件报错问题求助
修复Chart.js 3.x中Chart.register的插件注册错误
我刚帮你排查了问题,你遇到的Error: class does not have id是Chart.js 3.x的新要求导致的——所有注册的插件必须包含一个唯一的id属性,另外你代码里的chart实例访问方式也需要适配v3的结构变化。
下面是具体的修复步骤和完整代码:
问题根源
- 缺少插件id:Chart.js 3.x强制要求每个插件都要有唯一的
id属性,用来管理插件的注册/卸载,你的插件对象没有这个属性所以报错。 - Chart实例结构变化:v3里移除了
chart.chart这个嵌套层级,原来的chart.chart.width、chart.chart.ctx现在直接用chart.width、chart.ctx即可。
修复后的完整代码
// 先确保这些外部变量已经正确定义(根据你的业务逻辑赋值) // const sizeLabel1 = 250; // const colorLabel1 = "#FFFEFE"; // const positionLabel1 = 3.30; // const sizeLabel2 = 90; // const colorLabel2 = "#FFFEFE"; // const positionLabel2 = 2.70; // const sizeLabel3 = 150; // const colorLabel3 = "#FFFEFE"; // const positionLabel3 = 1.90; // const sizeLabel4 = 200; // const colorLabel4 = "#FFFEFE"; // const positionLabel4 = 1.50; Chart.register({ // 必须添加唯一的插件id,名字可以自定义,只要不重复就行 id: 'doughnut-center-text-plugin', beforeDraw: function(chart, args, options) { // 直接用chart.type判断更简洁,和chart.config.type效果一致 if (chart.type === 'doughnut') { const width = chart.width; const height = chart.height; const ctx = chart.ctx; let text; ctx.restore(); ctx.clearRect(0, 0, 3000, 3000); // 渲染第一个中心文本 let fontSize = (height / sizeLabel1).toFixed(2); ctx.fillStyle = colorLabel1; ctx.font = `400 ${fontSize * 13}px "Titillium Web"`; text = chart.config.options.elements.center.text1; const textX = Math.round((width - ctx.measureText(text).width) / 2); const textY = height / positionLabel1; ctx.fillText(text, textX, textY); // 渲染第二个中心文本 fontSize = (height / sizeLabel2).toFixed(2); ctx.fillStyle = colorLabel2; ctx.font = `Bold ${fontSize * 13}px "Titillium Web"`; text = chart.config.options.elements.center.text2; textX = Math.round((width - ctx.measureText(text).width) / 2); textY = height / positionLabel2; ctx.fillText(text, textX, textY); // 渲染第三个中心文本 fontSize = (height / sizeLabel3).toFixed(2); ctx.fillStyle = colorLabel3; ctx.font = `100 ${fontSize * 13}px "Titillium Web"`; text = chart.config.options.elements.center.text3; textX = Math.round((width - ctx.measureText(text).width) / 2); textY = height / positionLabel3; ctx.fillText(text, textX, textY); // 渲染第四个中心文本 fontSize = (height / sizeLabel4).toFixed(2); ctx.fillStyle = colorLabel4; ctx.font = `400 ${fontSize * 13}px "Titillium Web"`; text = chart.config.options.elements.center.text4; textX = Math.round((width - ctx.measureText(text).width) / 2); textY = height / positionLabel4; ctx.fillText(text, textX, textY); ctx.save(); } } });
关键修改说明
- 添加插件id:新增了
id: 'doughnut-center-text-plugin',这是v3插件的必填项,确保每个插件有唯一标识。 - 调整Chart实例访问路径:把所有
chart.chart替换成chart,适配v3的实例结构变化。 - 代码规范优化:把
var替换成let/const,让代码更符合现代JavaScript规范(可选,但推荐)。
如果运行后还有问题,先检查一下外部变量(sizeLabel1、colorLabel1等)是否正确定义并能被插件访问到,另外确保你引入的是Chart.js 3.x的正确版本。
内容的提问来源于stack exchange,提问作者pei-dev
相关产品推荐
相关产品推荐

