我正在使用react-chartjs-2生成一个图表,并从我的API中提取“类别”。类别的数量是动态的(将介于0和大约20之间,但最终取决于用户)。为甜甜圈图表的每个切片生成不同颜色的最佳方法是什么,所有这些都基于我的主要主题颜色(#3B73B4)?做渐变是否最好?
我的图形组件如下:
import React, { Component } from 'react';
import { Doughnut } from 'react-chartjs-2';
import colors from '../_styles/colors';
class CurrentPackGraph extends Component {
constructor(props) {
super(props);
this.state = {
categories: props.data.categories,
}
}
render() {
const data = {
labels: this.state.categories.map(c => c.name),
datasets: [{
data : this.state.categories.map(i => i.items.length),
backgroundColor : [
colors.darkPrimary,
'#36A2EB',
'#FFCE56',
],
hoverBackgroundColor: [
colors.darkPrimary,
'#36A2EB',
'#FFCE56',
],
}],
};
const chartOptions = {
maintainAspectRatio: false,
};
return (
<Doughnut
data={data}
options={chartOptions}
height={300}
/>
);
}
}
export default CurrentPackGraph;
您可以使用d3 scale library来实现:
import * as scale from "d3-scale";
// Set amount of categories
const length = 20;
// Generate color scale
const colors = scale
.scaleLinear()
.domain([0, length])
.range(["#fff", "#3B73B4"]);
// define some inline styles for illustration
const getBoxStyle = color => ({
margin: "20px",
backgroundColor: `${color}`
});
然后我们只使用生成的比例:
function App() {
const squares = [];
for (let i = 0; i < length; i++) {
squares.push(
<div style={getBoxStyle(colors(i))} key={i}>
{colors(i)} {i}
</div>
);
}
return <div className="App">{squares}</div>;
}
请在此处查看工作示例:https://codesandbox.io/s/p96vz6r5m0