I want to create this kind of color under a line chart.我搜索了一个解决方案,但找不到使用react-chart-js 2的。我想这样做,而不使用插件。
8tntrjer1#
好吧,这应该很容易开箱即用(不需要插件),你只需要设置backgroundColor属性为一个函数,输出一个梯度。(并将fill属性设置为所需的值)。虽然,我不能说你必须如何将其与react集成,这是简单的chartjs。
backgroundColor
fill
react
这里有一个演示,我将如何做到这一点:
梯度getGradient的函数取自上述示例。
getGradient
const lineChartData = { labels: [ '01/22', '02/22', '03/22', '04/22', '05/22', '06/22', '07/22', '08/22', ], datasets: [ { label: 'Profit', data: [2.4, 2.6, 2.23, 1.2, -2.2, -3.6, -1, 0.2], borderColor: '#0B9564', pointBackgroundColor: 'transparent', pointBorderColor: 'transparent', borderJoinStyle: 'bevel', // the following 2 properties are the ones that need to be set fill: { value: -25, }, backgroundColor: (context) => { const chart = context.chart; const {ctx, chartArea} = chart; if (!chartArea) { // This case happens on initial chart load return; } return getGradient(ctx, chartArea); }, }, ], }; let width, height, gradient; function getGradient(ctx, chartArea) { const chartWidth = chartArea.right - chartArea.left; const chartHeight = chartArea.bottom - chartArea.top; if (!gradient || width !== chartWidth || height !== chartHeight) { // Create the gradient because this is either the first render // or the size of the chart has changed width = chartWidth; height = chartHeight; gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top); gradient.addColorStop(1, 'rgba(0,128, 0, 1)'); gradient.addColorStop(.25, 'rgba(0,128, 0, 0)'); } return gradient; } const config = { type: 'line', data: lineChartData, options: { maintainAspectRatio: false, plugins: { legend: { position: 'right', labels: { usePointStyle: true, }, } }, } }; var myChart = new Chart( document.getElementById('chart'), config );
<script src="//cdn.jsdelivr.net/npm/chart.js"></script> <div class="chart" style="height:184px; width:350px;"> <canvas id="chart" ></canvas> </div>
**Checkout:**有关color properties / features和line Chart properties的详细信息,请参阅文档
1条答案
按热度按时间8tntrjer1#
好吧,这应该很容易开箱即用(不需要插件),你只需要设置
backgroundColor
属性为一个函数,输出一个梯度。(并将fill
属性设置为所需的值)。虽然,我不能说你必须如何将其与
react
集成,这是简单的chartjs。这里有一个演示,我将如何做到这一点:
梯度
getGradient
的函数取自上述示例。**Checkout:**有关color properties / features和line Chart properties的详细信息,请参阅文档