我正在尝试在画布中创建一条线。一切都进行得很顺利,直到我在这一部分卡住了:
import { Doughnut } from "react-chartjs-2";
import "chart.js/auto";
import { Chart, ChartData, ChartDataset, ChartOptions } from "chart.js";
function DoughnutChart(){
const doughnutLabelsLine = {
id: "doughnutLabelsLine",
afterDraw(chart: Chart<"doughnut">, args: any, options: ChartOptions) {
const {
ctx,
chartArea: { top, bottom, left, right, width, height },
} = chart;
chart.data.datasets.forEach((dataset, i) => {
// console.log(chart.getDatasetMeta(i));
chart.getDatasetMeta(i).data.forEach((datapoint, index) => {
console.log(dataset);
const { x, y } = datapoint.tooltipPosition();
//Object is possibly undefined
ctx.fillStyle = dataset?.borderColor[index];
ctx.fillRect(x, y, 2, 2);
});
});
},
};
//config...
//dataDoughnut
return (
<div className="col-span-6">
<Doughnut
data={dataDoughnut}
options={config}
width={200}
height={300}
plugins={[doughnutLabelsLine]}
/>
</div>
);
}
export default DoughnutChart;
我也试过把它放在if语句中,并使用感叹号,但没有用。我是不是漏掉了什么?
编辑:根据user2057925的建议进行了调整
环圈图标签缐
const doughnutLabelsLine = {
id: "doughnutLabelsLine",
afterDraw(chart: Chart<"doughnut">, args: any, options: ChartOptions) {
const {
ctx,
chartArea: { top, bottom, left, right, width, height },
} = chart;
chart.data.datasets.forEach((dataset, i) => {
// console.log(chart.getDatasetMeta(i));
chart.getDatasetMeta(i).data.forEach((datapoint, index) => {
console.log(dataset);
const { x, y } = datapoint.tooltipPosition();
ctx.save();
const borderColor = datapoint.options.borderColor as
| string
| CanvasGradient
| CanvasPattern;
ctx.fillStyle = borderColor;
// ctx.fillStyle = dataset?.borderColor[index];
ctx.fillRect(x, y, 10, 10);
ctx.restore();
});
});
},
};
1条答案
按热度按时间ykejflvf1#
我认为
undefined
错误与dataset
示例无关,而是由于borderColor
示例。无论如何,最好的办法是使用
datapoint.options.borderColor
,因为:1.您不需要数据集示例或索引
1.作为
ArcElement
的数据点在options
节点中提供其所有选项,即使它们被配置(使用默认值)。第一个