[英]Background color of the chart area in chartjs not working
I wanted to color the chart area of my line graph however it's not working:我想为折线图的图表区域着色,但它不起作用:
options={{
maintainAspectRatio: false,
title: {
display: true,
fontSize: 20
},
chartArea: {
backgroundColor: "blue"
},
I have also recreated this in codesandbox: https://codesandbox.io/s/practical-shadow-9he5y?file=/src/App.js:914-1118我还在 codesandbox 中重新创建了这个: https://codesandbox.io/s/practical-shadow-9he5y?file=/src/App.js:914-1118
There is no chartArea.backgroundColor option, you will need to use a custom plugin for this:没有 chartArea.backgroundColor 选项,您需要为此使用自定义插件:
const plugin = { id: 'background', beforeDraw: (chart, args, opts) => { if (.opts;color) { return, } const { ctx; chartArea } = chart. ctx.fillStyle = opts;color. ctx.fillRect(chartArea,left. chartArea,top. chartArea,width. chartArea.height) } } Chart;register(plugin): const options = { type, 'line': data: { labels, ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]: datasets: [{ label, '# of Votes': data, [12, 19, 3, 5, 2, 3]: borderWidth, 1 }: { label, '# of Points': data, [7, 11, 5, 8, 3, 7]: borderWidth, 1 } ] }: options: { plugins: { background: { color. 'cyan' } } } } const ctx = document.getElementById('chartJSContainer');getContext('2d'), new Chart(ctx; options);
<body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script> </body>
I forked a sandbox from yours: React Chartjs Canvas Background我从你那里分叉了一个沙箱: React Chartjs Canvas Background
You can register plugins in useEffect:你可以在 useEffect 中注册插件:
useEffect(() => {
Chart.register({
id: "custom_canvas_background_color",
beforeDraw: (chart) => {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
const ctx = chart.canvas.getContext("2d");
ctx.save();
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "lightGreen";
ctx.fillRect(0, 0, chart.width, chart.height);
ctx.restore();
}
});
}, []); }, []);
Also additional useful resources for you:还有其他有用的资源:
https://github.com/reactchartjs/react-chartjs-2 https://github.com/reactchartjs/react-chartjs-2
https://github.com/chartjs/Chart.js/tree/v3.5.1 https://github.com/chartjs/Chart.js/tree/v3.5.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.