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

2022-01-22 00:00:00 javascript chart.js

我想更改由 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/

相关文章