Gradient Chart
Example of creating gradient chart with the <Chart> component.
Edit the example and see the result right away: StackBlitz runs it in your browser.
Open in new tabView on GitHubOpen in StackBlitz
import type { ChartData, ChartArea} from 'chart.js'import { useRef, useEffect, useState} from 'react'import { Chart as ChartJS, CategoryScale, LineController, LinearScale, PointElement, LineElement, Tooltip, Legend} from 'chart.js'import { Chart } from 'react-chartjs-2'import { faker } from '@faker-js/faker'
ChartJS.register( LineController, CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend)
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']const colors = [ 'red', 'orange', 'yellow', 'lime', 'green', 'teal', 'blue', 'purple']
export const data = { labels, datasets: [ { label: 'Dataset 1', data: labels.map(() => faker.number.int({ min: -1000, max: 1000 })) }, { label: 'Dataset 2', data: labels.map(() => faker.number.int({ min: -1000, max: 1000 })) } ]}
function createGradient(ctx: CanvasRenderingContext2D, area: ChartArea) { const colorStart = faker.helpers.arrayElement(colors) const colorMid = faker.helpers.arrayElement( colors.filter(color => color !== colorStart) ) const colorEnd = faker.helpers.arrayElement( colors.filter(color => color !== colorStart && color !== colorMid) ) const gradient = ctx.createLinearGradient(0, area.bottom, 0, area.top)
gradient.addColorStop(0, colorStart) gradient.addColorStop(0.5, colorMid) gradient.addColorStop(1, colorEnd)
return gradient}
export function App() { const chartRef = useRef<ChartJS>(null) const [chartData, setChartData] = useState<ChartData<'bar'>>({ datasets: [] })
useEffect(() => { const chart = chartRef.current
if (!chart) { return }
const chartData = { ...data, datasets: data.datasets.map(dataset => ({ ...dataset, borderColor: createGradient(chart.ctx, chart.chartArea) })) }
setChartData(chartData) }, [])
return ( <Chart ref={chartRef} type='line' data={chartData} /> )}