首页 > 解决方案 > 图表js背景颜色

问题描述

我正在做一些图表,我需要帮助。我需要创建一个水平条形图,它具有一些与背景颜色相关的颜色值,最大数据为 5 条。

例如,我需要为以下 x 轴值设置背景颜色:

0 - 10 ->白色

10 - 16 ->黄色

16 - 20 ->绿色

20 - 30 ->橙色

> 30 ->红色

我有以下代码:

new Chart.Chart(($("#grahe")).getContext('2d'), <any>{
            type: 'horizontalBar',
            data: data,
            plugins: [{
                beforeDraw: function (chartInstance: any, easing) {
                    var ctx = chartInstance.chart.ctx;

                    var meta = chartInstance.getDatasetMeta(0);

                    var start = meta.data[3]._model.x;
                    var stop = meta.data[1]._model.x;

                    console.log(start, stop);


                    ctx.save();
                    ctx.fillStyle = "red";
                    console.log(chartArea);
                    ctx.fillRect(start, chartArea.top, stop - start, chartArea.bottom - chartArea.top);
                    ctx.restore();

                }
            }],
            options: {
                plugins: {
                    datalabels: {
                        color: (context) => {
                            return "white";
                        },
                        font: {
                            family: 'DINPro',
                            size: 0
                        }
                    },
                },
                tooltips: {
                    mode: 'index',
                    bodyFontSize: 14,
                    titleFontSize: 14
                },
                responsive: true,
                legend: {
                    display: false
                },
                scales: {
                    xAxes: [
                        {
                            stacked: true,
                            ticks: {
                                min: 0
                            },
                            gridLines: {
                                color: "#555",
                                zeroLineColor: "#666"
                            }
                        }
                    ],
                    yAxes: [
                        {
                            barThickness: 20,
                            stacked: true,
                            ticks: {
                                min: 0,
                                callback: (value, index, values) => {
                                    return value;
                                }
                            },
                            gridLines: {
                                display: false,
                                color: "#555",
                                zeroLineColor: "#666"

                            }
                        }
                    ]
                }
            }
        });

但这是根据图表的数据填充背景,而不是 x 轴。

有什么想法吗?

谢谢

标签: javascriptcanvascharts

解决方案


对于寻找解决方案的人。我找到了一种使用 chartjs-plugin-annotation 的方法。

如果你想看看那里:)


推荐阅读