使用Chart.js,我可以为图表标题中的每行文本指定不同的字体大小吗?

wmtdaxz3  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(178)

我正在使用Chart.js版本:2.7.3
我的图表标题有三行。我想将第一行的字号设为16,第二行的字号设为14,第三行的字号设为12。我不确定是否可行,还没有找到方法。
下面是我的代码的一部分,它定义了我的图表选项...

options: {
    title: {
        display: true,
        // Supply the title as an array and each array index prints on a separate line in the title section
        text: ['My Chart','Last Month', 'Local Time'],
        fontSize: 16,
        callbacks: {
            drawTitle: function(pt, vm, ctx, opacity) {
                    console.log("title.length: " + title.length);
                    var title = vm.title;

                    if (title.length) {
                        ctx.textAlign = vm._titleAlign;
                        ctx.textBaseline = 'top';

                        var titleFontSize = vm.titleFontSize;
                        var titleSpacing = vm.titleSpacing;

                        ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity);
                        ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);

                        var i, len;
                        for (i = 0, len = title.length; i < len; ++i) {
                            ctx.fillText(title[i], pt.x, pt.y);
                            pt.y += titleFontSize + titleSpacing; // Line Height and spacing

                            if (i + 1 === title.length) {
                                pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
                            }
                        }
                    }
                }
            }
        },

我知道你可以指定一个“fontSize”,但这适用于图表标题中的所有文本。我希望每行文本都有一个不同的fontSize。我尝试指定一个回调,但当我在Chrome F12 devtools中检查时,我看不到console.log()消息。
在Chart.js中是否有一种方法可以为图表标题中的每一行指定不同的fontSize?
谢谢你,谢谢你

解决方案更新

我已经接受了Edi卡洛斯的回答,因为它给出了有关如何将格式化文本附加到画布元素的有用建议,并且这可以在Chart.js动画回调中完成。
我的图表是一个启用了工具提示的散点图。使用接受的解决方案,当悬停在绘制点上时,fillText可能会消失或更改屏幕上的位置。我发现如果我使用F12 Chrome开发工具,文本也会消失。在接受的答案中,jsfiddle中也会发生同样的情况...如果您启用了工具提示...请尝试将鼠标悬停在条形图上或按F12。
要阻止fillText在将鼠标悬停在工具提示上时移动位置,我发现必须指定:

ctx.textBaseline = 'top';
ctx.textAlign = 'center';

为了防止fillText在按F12键时消失,我发现我必须用绝对位置对canvas元素进行CSS样式化。


# canvas{

    position:absolute;
}

下面是Chart.js选项中的一段代码,它显示了如何为Chart.js图表标题中的每行文本指定不同的字体大小和样式:

options: {
    animation: {
        onProgress: function(animation) {
            ctx.textBaseline = 'top';
            ctx.textAlign = 'center';

            // Set the font size and text position for the 2nd row in the Chart title
            ctx.font = "bold 14px 'Helvetica Neue', Helvetica, Arial, sans-serif";
            ctx.fillStyle = "#666";
            ctx.fillText("Last 24 Hours", 610, 32);

            // Set the font size and text position for the 3rd row in the Chart title
            ctx.font = "bold 12px 'Helvetica Neue', Helvetica, Arial, sans-serif";
            ctx.fillStyle = "#666";
            ctx.fillText("Local Time | Limit=None", 610, 53);
        }
    },      
    title: {
        display: true,
        text: ['Sensor Chart','             ', '                         '],
        fontSize: 16
        }
    }

Chart.js允许您提供一个字符串数组作为标题,然后将每个数组索引打印在单独的一行上。[]数组索引1和2,以便在图表标题中有空白空间来放置ctx.fillText()。

建议添加到Chart.js中

总的来说,这仍然是一个有点笨拙的方法。我认为Chart.js应该有一个更集成的解决方案。类似于用同样的方法,你可以指定多个y轴,每个y轴都有自己的属性,使用:

yAxes: [
        {
            id: 'A',
            ..
            ..
        },
        {
            id: 'B',
            ..
            ..
        }
    ]

如果您可以在图表标题中为多个行指定样式,则会非常棒,如下所示:

title: {
    display: true,
    titleRows: [
            {
                id: 'A',
                text: 'Row1',
                fontSize: 16,
                ..
            },
            {
                id: 'B',
                text: 'Row2',
                fontSize: 14,
                ..
            },
            {
                id: 'C',
                text: 'Row3',
                fontSize: 12,
                ..
            }
        ]
    }
u4vypkhs

u4vypkhs1#

您可以使用fillText()方法使用Chart.js版本:2.7.3
使用fillText()在画布上写入**“Network!"“Stackoverflow”**(使用渐变):

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.font = "20px Georgia";
ctx.fillText("Network", 10, 50);

ctx.font = "30px Verdana";
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0"," magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillText("Stackoverflow", 10, 90);

fillText()方法在画布上绘制填充文本。文本的默认颜色是黑色。使用font属性指定字体和字体大小,并使用fillStyle属性以另一种颜色/渐变呈现文本。
我的Fiddle示例

更新**-〉**您可以使用动画回调(onProgress或onComplete)来执行此操作,例如:

options: {
        animation: {
            onProgress: function(animation) {
                // code above
            }
        }
    }

**更新2 -〉**完整代码

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            data: [2, 2, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
    tooltips: {
         enabled: false
    },
      legend: {
          display: false
      },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        },
        animation: {
            onProgress: function(animation) {
                var c = document.getElementById("myChart");
                var ctx = c.getContext("2d");

                ctx.font = "20px Georgia";
                ctx.fillText("1 - Network", 45, 30);                

                ctx.font = "30px Verdana";
                // Create gradient
                var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
                gradient.addColorStop("0", "magenta");
                gradient.addColorStop("0.5", "blue");
                gradient.addColorStop("1.0", "red");
                // Fill with gradient
                ctx.fillStyle = gradient;
                ctx.fillText("2 - Stackoverflow", 45, 70);                
            }
        }
    }
});

完整Fiddle
我希望能帮上忙!

mo49yndu

mo49yndu2#

使用ChartJS副标题选项:
第一个

相关问题