简体   繁体   English

Chartjs 区域背景颜色

[英]Chartjs area background color

彩色图形背景

How to change the chart area background color using chart js?如何使用图表js更改图表区域背景颜色? I want my chart looks like this.我希望我的图表看起来像这样。

You need to implement a plugin to fill the canvas.您需要实现一个插件来填充 canvas。 Below a sample with fixed colors.下面是固定 colors 的示例。

You can also have a look to the CHart.js sample: https://www.chartjs.org/docs/latest/samples/plugins/quadrants.html您还可以查看 CHart.js 示例: https://www.chartjs.org/docs/latest/samples/plugins/quadrants.html

 const ctx = document.getElementById("myChart"); const plugin = { id: 'bgColorArea', beforeDraw(chart, args, options) { const {ctx, chartArea: {left, top, width, bottom}, scales: {x, y}} = chart; const endTop = y.getPixelForValue(35); const endMid = y.getPixelForValue(10); ctx.save(); ctx.fillStyle = 'lightCoral'; ctx.fillRect(left, top, width, endTop - top); ctx.fillStyle = 'lightGreen'; ctx.fillRect(left, endTop, width, endMid - endTop); ctx.fillStyle = 'lightGrey'; ctx.fillRect(left, endMid, width, bottom - endMid); ctx.restore(); } }; const myChart = new Chart(ctx, { type: 'line', plugins: [plugin], data: { labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'test', data: [50, 35, 45, 47, 10, 3, 27], borderWidth: 2, borderColor: 'black' }] } });
 .myChartDiv { max-width: 600px; max-height: 400px; }
 <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script> <html> <body> <div class="myChartDiv"> <canvas id="myChart" width="600" height="400"/> </div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM