chart.js 中折线图的背景颜色颜色、背景、折线图、chart

2023-09-09 21:04:51 作者:睁眼说 ﹏゛瞎话

我想更改由 chart.js 生成的折线图的背景颜色.似乎没有这个选项,文档也没有帮助.在互联网上广泛搜索没有产生任何结果.这可能吗?

I would like to change the background colour of the line graph produced by chart.js. There doesn't appear to be an option for this, and the documentation doesn't help. Extensive searching on the interweb has yielded no results. Is this possible?

我必须承认我对 HTML5 画布了解不多,所以我有点挣扎!

I must confess I don't really know much about the HTML5 canvas so I'm struggling a bit!

推荐答案

使用 v2.1 的 Chart.js,您可以编写自己的插件来做到这一点

With v2.1 of Chart.js, you can write your own plugin to do this

预览

脚本

Chart.pluginService.register({
    beforeDraw: function (chart, easing) {
        if (chart.config.options.chartArea && chart.config.options.chartArea.backgroundColor) {
            var helpers = Chart.helpers;
            var ctx = chart.chart.ctx;
            var chartArea = chart.chartArea;

            ctx.save();
            ctx.fillStyle = chart.config.options.chartArea.backgroundColor;
            ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
            ctx.restore();
        }
    }
});

然后

...
options: {
    chartArea: {
        backgroundColor: 'rgba(251, 85, 85, 0.4)'
    }
}
...

小提琴 - http://jsfiddle.net/rrcd60y0/