Integrating CanvasJS with Svelte: A Step-by-Step Guide

Vishwas R
2 min readSep 30, 2024

--

CanvasJS is a charting library that allows developers to add interactive and responsive charts to app with ease. It can seamlessly be integrated with Svelte, a modern JavaScript framework that compiles components into highly efficient vanilla JavaScript at build time, offering excellent performance and a clean syntax.

CanvasJS Column Chart in Svelte

In this article, let’s walk through the process of integrating CanvasJS with Svelte to create visually appealing charts.

Step 1: Setting Up Your Svelte Project

First, you’ll need to set up a new Svelte project. If you haven’t already, install Svelte using the following command:

npx degit sveltejs/template canvasjs-svelte-app
cd canvasjs-svelte-app
npm install

This will create a new Svelte project in a directory called canvasjs-svelte-app.

Step 2: Installing CanvasJS

Next, install CanvasJS via npm:

npm install @canvasjs/charts

Step 3: Creating a Svelte Component for CanvasJS

Create a new Svelte component, Chart.svelte, in the src directory. This component will be responsible for rendering the CanvasJS chart.

<script>
import { onMount } from 'svelte';
import CanvasJS from 'canvasjs';

let chart;

onMount(() => {
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: ”light2”,
title: {
text: "Column Chart in Svelte"
},
data: [{
type: "column",
dataPoints: [
{ label: "Apple", y: 10 },
{ label: "Orange", y: 15 },
{ label: "Banana", y: 25 },
{ label: "Mango", y: 30 },
{ label: "Grape", y: 28 }
]
}]
});
chart.render();
});
</script>

<style>
#chartContainer {
height: 370px;
width: 100%;
}
</style>

<div id="chartContainer"></div>

Step 4: Using the Chart Component

Now, you can use the Chart.svelte component in your main App.svelte file to display the chart.

<script>
import Chart from './Chart.svelte';
</script>

<main>
<h1>CanvasJS with Svelte</h1>
<Chart />
</main>

Step 5: Running Your Svelte App

Finally, run your Svelte app to see the CanvasJS chart in action:

npm run dev

Open your browser and navigate to http://localhost:5000 to see your chart.

Integrating CanvasJS with Svelte is straightforward and allows you to leverage the powerful charting capabilities of CanvasJS within the efficient and modern framework of Svelte. This combination can be particularly useful for creating dynamic and interactive data visualizations in your web applications.

By following the steps outlined in this article, you should be able to set up and customize CanvasJS charts in your Svelte projects with ease. Happy coding!

--

--

Vishwas R
Vishwas R

Written by Vishwas R

<< Engineer || Software Developer || Techie || Cricketer || Traveler || Blogger >>

No responses yet