ChartJS6.2- fillText()总是使用最后的ctx.font设置

bfrts1fy  于 2023-05-17  发布在  Chart.js
关注(0)|答案(1)|浏览(148)

我的最终目标是使用ChartJS库将文本写入Doughnut图表的中心,并使用不同的字体参数对不同部分的文本进行处理。
现在,将文本添加到环形图的中心不是问题。我遇到的问题是所有的fillText()都使用了最后的ctx.font值。
请注意,使用较旧版本的ChartJS时,这不会有任何问题。
工作示例(旧版本的lib):https://jsfiddle.net/os2L3e5b/工作示例(ChartJS 6.2):http://jsfiddle.net/qu4ztg8m/8/
因此,在http://jsfiddle.net/qu4ztg8m/8/中,我创建了两个插件,它们只是在画布上以不同的颜色绘制。
同样,重点是我可以使用不同的字体添加多个文本片段。

clj7thdc

clj7thdc1#

我认为你应该包括你的上下文2D语句保存和恢复上下文(in2插件)如下:

ctx.save(); // saves previous config
                ctx.font = "bold 16px Arial";
                ctx.fillStyle = 'rgb(0, 0, 255,1)';
                ctx.fillText( 20, 70, 130 );
                ctx.restore(); // restores previous config

插件:

var chartjs_draw_in_doughnut_plugin = {
  afterDatasetsDraw: function(chart, args, options) {
    // Get ctx from string
    const ctx = chart.ctx;
    // saves the state of the canvas
    ctx.save();
    // ------------
    // FIRST LABEL
    // ------------
    // creates new path to draw something with the same config
    ctx.beginPath();
    // sets config  
    ctx.font = "bold 16px Arial";
    ctx.fillStyle = 'rgb(0, 0, 255,1)';
    ctx.fillText( 20, 70, 130 );
    // fills text
    ctx.fill();
    // ------------
    // SECOND LABEL
    // ------------
    // creates new path to draw something with the same config
    ctx.beginPath();
    // sets config  
    ctx.font = "regular 16px Arial";
    ctx.fillStyle = 'rgb(0, 0, 255,0.5)';
    ctx.fillText( ' / 50', 85, 130 );
    // fills text
    ctx.fill();
    // restores the state of the canvas
    ctx.restore();
  }
}

相关问题