Chartjs-How to convert chart.js library chart to image in pure node.js without using HTML and CSS?

0👍

Here is an example of turning an nchart into a .png and base64 encoding it into an attachment:

const Canvas = require('canvas');
const Chart = require('nchart');

...

if (turnContext.activity.text == "chart")
{                
        let canvas = Canvas.createCanvas(500, 500);
        let ctx = canvas.getContext('2d');

        new Chart(ctx).Pie(
            [
                {
                    "value": 50
                    , "color": "#E2EAE9"
                }
                , {
                    "value": 100
                    , "color": "#D4CCC5"
                }
                , {
                    "value": 40
                    , "color": "#949FB1"
                }
            ]
            , {
                scaleShowValues: true
                , scaleFontSize: 24
            }
        );

        const buf = canvas.toBuffer('image/png', { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE })  
        const reply = { type: ActivityTypes.Message };
        const base64Image = Buffer.from(buf).toString('base64');
        reply.attachments = [{
            name: 'architecture-resize.png',
            contentType: 'image/png',
            contentUrl: `data:image/png;base64,${ base64Image }`
        }];
        reply.text = 'Chart';
        turnContext.sendActivity(reply);
}

Bot Framework Emulator:
enter image description here

Leave a comment