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

ChartJS 3.5版本beforeDraw插件适配异常问题求助

ChartJS 3.5版本beforeDraw插件适配方案

核心适配改动

  • 3.x版本插件注册强制要求声明id属性,否则插件不会生效
  • 钩子入参的chart对象就是顶层实例,移除了2.x版本多余的嵌套层级,原代码中chart.chart.chart、chart.chart.width这类写法全部需要简化
  • 调整canvas上下文的save/restore调用顺序,避免绘图状态异常

适配后代码

Chart.register({
  // 3.x强制要求插件声明唯一id
  id: 'doughnutCenterText',
  beforeDraw: function(chart, args, options) {
    if(chart.config.type == 'doughnut') {
      const width = chart.width;
      const height = chart.height;
      const ctx = chart.ctx;
      
      var text;
      
      ctx.save();
      ctx.clearRect(0, 0, 3000, 3000);
      
      fontSize = (height / sizeLabel1).toFixed(2);
      ctx.fillStyle = colorLabel1;
      ctx.font = '400 ' + fontSize * 13 + 'px "Titillium Web"';
      text = chart.config.options.elements.center.text1;
      textX = Math.round((width - ctx.measureText(text).width) / 2);
      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.restore();
    }
  }
});

注意事项

  • 代码中用到的sizeLabel1、colorLabel1、positionLabel1等变量需确保在插件执行作用域内可访问
  • 若自定义的center配置项报错,可在初始化图表时提前在options.elements中声明center对象结构,避免读取属性时报错

内容的提问来源于stack exchange,提问作者pei-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:15:02