chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
64.23k stars 11.89k forks source link

backgroundColor to allow type string[] and scriptable string[] #10123

Open LovelyAndy opened 2 years ago

LovelyAndy commented 2 years ago

Feature Proposal

I've been attempting to get variable backgroundcolors for a doughnut charts based on their value. Each would have a variable color, followed by a base color (grey). The idea I had was to have a few if statements to check the value and then render the correct array of colors, but the current typing does not allow for an array. It would be a great fix to allow you to use arrays as the background color with ts support.

There's a type mistake in the source code where it doesn't allow something that's possible with just JS. It renders correctly if I cast to any but TS doesn't allow it:

ChartOptions<'doughnut'>
// throws a Type error at backgroundColor
{
  backgroundColor: ((ctx) => {
    return ['blue', 'grey']
  })
}

Looking at the source code, I found that now it says:

backgroundColor: Scriptable<Color, ScriptableContext<TType>>;
// only accepts string or a fn that returns a string

it will allow a string array if I change it to

backgroundColor: ScriptableAndArray<Color, ScriptableContext<TType>>;

but what I need is to allow a function that returns a string array. Wasn't sure how to do that!

Possible Implementation

No response

LeeLenaleee commented 2 years ago

The scriptable function is evaluated for each individual part, and it is not supported to return an array of colors for each individual slice so the current behaviour is correnct

Seems I am wrong

teodorachiosa commented 2 months ago

+1

We had this error: image "Type 'string' is not assignable to type 'string[]'." const backgroundColorArray: string[] = legend.chart.data.datasets[0].backgroundColor

We had to fix this by casting to string[], which is a bit weird... const backgroundColorArray: string[] = legend.chart.data.datasets[0].backgroundColor as string[];

In Chart.js' documentation, the backgroundColor is clearly used with an array of colors. https://www.chartjs.org/docs/latest/charts/doughnut.html#pie image

So this should be supported in TS.