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 ' 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>
3

2 Answers

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.)

1

Your code, copied directly into a Svelte REPL without modification seems to work fine:

enter image description here

So the issue is probably somewhere else.

  • Are there any errors in the browser dev console?
  • Errors in the terminal? (Where you started SvelteKit.)

My guess is there is a JS error, probably related to importing Chart.js.

  • Your page would render a blank canvas even if there were JS errors.
  • Did you actually install the Chart.js modules? (npm install ...)

Here is a similar problem I solved:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like