Is there anything missing to use Chart.js on a Svelte app?
I am new to Svelte and having trouble displaying a graph using Chart.js on a SvelteKit page.
First, I tried to put a canvas and confirmed that it worked, as the code below shows a black canvas on a page if you comment out the onMount function. However, it doesn't show anything after adding the onMount part. There is no error indication in the browser and terminal console, so I am stuck with it.
I use the latest version of Sveltekit and Chart.js. Is there anything missing?
<script>
import { onMount } from 'svelte';
import Chart from 'chart.js/auto';
let data = [20, 100, 50, 12, 20, 130, 45];
let labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
let ctx;
let canvas;
onMount(() => {
ctx = canvas.getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: 'Unit Sales',
data: data
}
]
}
});
});
</script>
<canvas bind:this={canvas} width={32} height={32} />
<style>
canvas {
width: 100%;
height: 100%;
background-color: #666;
}
</style>
Comments
Post a Comment