To apply canvas gradients to your charts, use the bind:chart directive on a Svelte component to capture the chart instance. Once the component is mounted, you can access the canvas context via chart.ctx to create a CanvasGradient (e.g., using createLinearGradient).
Important Requirements:
- Lifecycle: You must create the gradient inside an
onMount block (or similar lifecycle hook) to ensure chart.ctx and chart.chartArea are fully initialized. - Plugins: If you are using the
fill: true option to apply the gradient to the area under a line, you must register the Filler plugin from chart.js. - Application: Apply the resulting gradient object to the
backgroundColor property within your data object.
<script>
import { onMount } from 'svelte';
import { Line } from 'svelte-chartjs';
import {
Chart as ChartJS,
Title, Tooltip, Legend,
LineElement, LinearScale, PointElement, CategoryScale, Filler,
} from 'chart.js';
// 1. Register necessary plugins (Filler is required for area fills)
ChartJS.register(
Title, Tooltip, Legend,
LineElement, LinearScale, PointElement, CategoryScale, Filler
);
let chart = $state(null);
let data = $state({
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Sales',
data: [65, 59, 80, 81, 56, 55, 40],
fill: true,
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
tension: 0.4,
}],
});
onMount(() => {
if (!chart) return;
// 2. Access the context and chart area to create the gradient
const ctx = chart.ctx;
const gradient = ctx.createLinearGradient(0, 0, 0, chart.chartArea.bottom);
gradient.addColorStop(0, 'rgba(75, 192, 192, 0.6)');
gradient.addColorStop(1, 'rgba(75, 192, 192, 0.0)');
// 3. Update the data with the gradient
data = {
...data,
datasets: [{ ...data.datasets[0], backgroundColor: gradient }],
};
});
</script>
<!-- 4. Bind the chart instance -->
<Line bind:chart {data} options={{ responsive: true }} />