如何在不使用HTML和CSS的情况下将chart.js库图表转换为纯node.js中的图像?

问题描述 投票:0回答:1

目前我需要一个在Microsoft Bot框架中显示的图表。所以我使用chart.js库来生成图表。现在我想将它转换为.png图像格式。所以我可以在Bot中显示。

那么如何在不使用HTML和CSS的情况下将chart.js图表​​转换为node.js中的图像。

这是我的图表代码

var Canvas = require('canvas')
  , canvas = Canvas.createCanvas(500, 500)
  , ctx = canvas.getContext('2d')
  , Chart = require('nchart')
  , fs = require('fs');

var myDoughnutChart = new Chart(ctx, {
    type:'polarArea',
data:{
labels:['Strength','Skill','Health','Speed','Luck'],
datasets:[
{
label:'Points',
backgroundColor:['#f1c40f','#e67e22','#16a085','#16a085','#16a085'],
data:[10,20,55,30,10]
}
]
},
options: {
    animation:{
        animateScale : true
    }  
 }
});
node.js chart.js
1个回答
0
投票

以下是将nchart转换为.png和base64将其编码为附件的示例:

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框架模拟器:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.