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

时间:2019-03-06 10:53:59

标签: node.js chart.js

当前,我需要一个图表来显示在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
    }  
 }
});

1 个答案:

答案 0 :(得分: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 Framework模拟器: enter image description here