Search code examples
javascriptchartssveltesveltekit

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>


Solution

  • The container is probably the problem. The docs state:

    Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes.

    You can for example wrap the canvas in a div and size that explicitly:

    div { width: 50vw; height: 50vh; }
    

    (The rules for width/height of the canvas itself do nothing and will be automatically overridden by Chart.js.)