ChartJS Only Show Large Font Size for a Specific Tick

前端 未结 2 1751
有刺的猬
有刺的猬 2021-01-28 10:00

I am attempting to emphasize a specific value on the X-Axis if it meets a specific condition.

For example, in my codepen I want to only change the font size of the \'blu

2条回答
  •  故里飘歌
    2021-01-28 10:36

    Chartjs doesn't have a public api to do this but you can modify internal _ticks on beforeDraw and make the label "Blue" as major: true then that label will be drawn using the major styling in tick configuration options.

    Also use this with caution since it relies on internal implementation and thus might break in future releases (very unlikely to happen but just saying).

    var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 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: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }],
                xAxes: [{
                    ticks: {
                        fontSize: 16,
                        major: {
                          fontSize: 20
                        }
                    }
                }]
            }
        }, 
        plugins: [{
            beforeDraw: function({ chart }, options) {
                chart.boxes
                .find(box => box.id === "x-axis-0")
                ._ticks
                .find(tick => tick.label === "Blue")
                .major = true;
            }
        }]
    });
    
    

    PS: Just in case someone is wondering how I know this internal implementation I searched fillText in chartjs github source code and console.log(myChart) xD

提交回复
热议问题