我可以为图表标题中的每一行文本指定不同的字体大小吗? [英] Can I specify a different font size for each row of text in Chart Title?

查看:85
本文介绍了我可以为图表标题中的每一行文本指定不同的字体大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Chart.js版本:2.7.3

I am using Chart.js Version: 2.7.3

我的图表标题有三行。我想使第一行的字体大小为16,然后使第二行的字体大小为16,第三行的字体大小为12。我不确定是否有可能,并且还没有找到方法。

My Chart Title has three rows. I'd like to make the top row font size 16 then the second 14 and the third 12. I'm not sure if it's possible and haven't found a way.

这是我的代码的一部分,用于定义图表的选项...

Here is a portion of my code that defines the options for my Chart...

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()消息。

I know you can specify a "fontSize" but this applies to all Text in the Chart Title. I want a different fontSize for each row of text. I tried specifying a Callback but I don't see the console.log() message when I check in Chrome F12 devtools.

在Chart.js中有一种方法可以为图表标题中的每一行指定不同的fontSize?

Is there a way in Chart.js to specify a different fontSize for each row in the Chart Title?

谢谢!

我接受了Edi Carlos的回答,因为这为如何将格式化文本附加到画布元素提供了有用的建议,并且可以在Chart.js动画中完成

I have accepted the answer from Edi Carlos because this gave the helpful advice about how to attach formatted text to a canvas element and that this can be done within a Chart.js animation callback.

我的图表是启用了工具提示的散点图。使用公认的解决方案,将鼠标悬停在绘制的点上时,fillText可能会消失或更改屏幕上的位置。我发现如果使用F12 Chrome开发工具,文字也会消失。 jsfiddle在接受的答案中也会发生同样的情况...如果启用工具提示...请尝试将鼠标悬停在条形图上或按F12键。

My Chart is a Scatter Plot with Tooltips enabled. With the accepted solution when hovering over a plotted point the fillText may disappear or change position on the screen. I found the text would also disappear if I used F12 Chrome Dev Tools. The same happens in the jsfiddle in the accepted answer... if you enable Tooltips... try hovering over a bar chart or hitting F12.

要从以下位置停止fillText悬停在工具提示上时移动位置,我发现我必须指定:

To stop the fillText from shifting position when hovering over a ToolTip I found I had to specify:

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

要阻止fillText在按F12时消失,我发现我必须使用绝对样式对CSS画布元素进行样式设置

To stop the fillText from disappearing when hitting F12 I found I had to CSS style the canvas element with absolute position.

#canvas{
    position:absolute;
}

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

Here is a section of the code in my Chart.js options that shows how to specify a different font size and style for each row of text you may have in a Chart.js Chart Title:

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 lets you supply an array of strings as the title. Then each array index prints out on a separate line. I left spaces in the text: [] array index 1 and 2 so there would be blank space in the Chart Title to position the ctx.fillText() into.

总体而言,这样做仍然感觉有些拙劣。我认为Chart.js应该有一个更集成的解决方案。类似的方式,您可以使用以下方法指定多个y轴,每个y轴都具有自己的属性:

Overall this still feels like a slightly hacky way to do it. I think Chart.js should have a more integrated solution. Something like in the same way you can specify more than one y-axis each with its own properties using:

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

如果您可以为图表标题中的多行指定样式,例如:

It would be great if you could specify styling for multiple rows in a Chart Title with something like:

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


推荐答案

您可以使用Chart.js版本的 fillText()方法:2.7.3

You can to use fillText() Method using Chart.js Version: 2.7.3

使用fillText()在画布上编写网络! Stackoverflow (带有渐变):

Write "Network!" and "Stackoverflow" (with gradient) on the canvas, using fillText():

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属性以另一种颜色/渐变呈现文本。

The fillText() method draws filled text on the canvas. The default color of the text is black. Use the font property to specify font and font size, and use the fillStyle property to render the text in another color/gradient.

我的小提琴示例

更新 -> 您可以使用动画回调(onProgress或onComplete)来做到这一点,例如:

Update -> You can use Animations Callbacks (onProgress or onComplete) to do that eg:

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);                
            }
        }
    }
});

完整提琴

我希望有所帮助!

这篇关于我可以为图表标题中的每一行文本指定不同的字体大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆