Chart.js -对图形着色时覆盖继承的颜色

de90aj5v  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(192)

我正在用ChartJS创建图表,但它们似乎继承了某个父元素的默认颜色。图表看起来像这样:

我根据用户的选择动态地创建图表。ChartJS图表接受一个基元数组或对象数组作为图表数据。我使用下面的函数创建图表对象,然后使用这些对象的数组作为ChartJS的参数:

function getChartDataObject(data){
    var title = data['metadata']['title'];
    var color = random_rgba();
    console.log(`Color: ${color}`);
    var dataObject = {
        label: title,
        data: data['scaled_interval'],
        color: color,
        fill: false,
        lineTension: 0,
        radius: 1,
    }
    return dataObject;
}

然后我使用以下函数创建主图表:

function createIntervalChart(intervalDataObjects, datetimeInterval) {
    const cnvs = document.createElement('canvas');
    const ctx = $(cnvs);

    var data = {
        labels: datetimeInterval,
        datasets: intervalDataObjects,
    }

    var options = {
        responsive: true,
        title: {
            display: true,
            position: "top",
            text: "Projected Load Profiles",
            fontSize: 18,
            fontColor: "#111",
        },
        legend: {
            display: true,
            position: "bottom",
            labels: {
                fontColor: "#333",
                fontSize: 16
            }
        },
        elements: {
            point: {
                radius: 0
            }
        },
        plugins: {
            zoom: {
                zoom: {
                    wheel: {
                        enabled: true
                    },
                    pinch: {
                        enabled: true
                    },
                    mode: 'xy',
                }
            },
            title: {
                text: "Estimated Load Profiles"
            }
        }
    };

    var chart = new Chart(ctx, {
        type: "line",
        data: data,
        options: options
    });

    return cnvs;
}

当我检查控制台时,我看到random_rgb()函数创建了不同的颜色,但它们都变成了灰色。

Color: rgba(215,231,183,0.6)
Color: rgba(253,61,199,0.1)
Color: rgba(27,15,88,0.1)

有人知道如何创建一个ChartJS图表与自定义颜色?或如何覆盖继承的样式为这些图表?谢谢

lyr7nygr

lyr7nygr1#

color不是折线图的有效dataset属性。请使用borderColor,也可以使用backgroundColor(将用于绘制图例标签框)。

function getChartDataObject(data){
    var title = data['metadata']['title'];
    var color = random_rgba();
    console.log(`Color: ${color}`);
    var dataObject = {
        label: title,
        data: data['scaled_interval'],
        borderColor: color, // <- to be changed
        fill: false,
        lineTension: 0,
        radius: 1,
    }
    return dataObject;
}

有关详细信息,请参阅Chart.js文档中的“数据集属性”。

相关问题