Using Chart.js in Nodejs server and exporting it as an image.

Ekta Prasad
2 min readDec 12, 2020

--

Photo by Luke Chesser on Unsplash

There is a very simple way to use chart.js on an HTML page, one just has to include the CDN URL in ‘src’ and draw on canvas in the script tag. But this script tag runs when you open the file in the browser, what if you want to run the code on the node.js server. For that, you can continue reading my post.

For making a chart on node.js, first, you will have to install ‘chartjs-node-canvas’ and chart.js

npm i chart.jsnpm i chartjs-node-canvas

Now require it into your file :

const {CanvasRenderService} = require('chartjs-node-canvas');

For using the chartjs service, you will have to write:

const canvasRenderService = new CanvasRenderService(width, height, chartCallback);

Here you will be providing width, height, and the callback function.

For converting the chart to an image, you use ‘renderToDataURL’. This converts the chart into a base64 image URL. By default, it converts the image to png format. In the configuration, you pass the customized values as per your need.

canvasRenderService.renderToDataURL(configuration);

The configuration is similar to what you use in html or script. You can find the documentation here.

Below is an example of line graph.

And this is how you make it work on node.js server. You can use the image to any file now whether ejs or html. Hope it helps.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ekta Prasad
Ekta Prasad

Responses (4)

Write a response