首页 > 解决方案 > 画布渲染服务 [chartjs-node-canvas npm] 渲染到缓冲区需要太多时间来处理 chart.js 的图表?

问题描述

我正在使用chartjs-node-canvas来生成我的图表,处理图表需要 35 秒的时间,我想知道,出了什么问题,或者它是否应该花费这么多时间?

这是我的 app.js (node.js) 代码:

const fs=require( 'fs' );

// console.time( 'do this', Date.now() );
var now=Date.now();
console.log( "time elapsed0:", Date.now()-now );

const { CanvasRenderService }=require( 'chartjs-node-canvas' );
console.log( "time elapsed1:", Date.now()-now );

// const { time }=require( 'console' );

const width=400;
const height=400;
const configuration={
    type: 'bar',
    data: {
        labels: [ 'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange' ],
        datasets: [ {
            label: '# of Votes',
            data: [ 12, 19, 3, 5, 2, 3 ],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        } ]
    },
    options: {
        animation: {
            duration: 0 // general animation time
        },
        hover: {
            animationDuration: 0 // duration of animations when hovering an item
        },
        responsiveAnimationDuration: 0, // animation duration after a resize
        scales: {
            yAxes: [ {
                ticks: {
                    beginAtZero: true,
                    callback: ( value ) => '$'+value
                }
            } ]
        }
    }
};
console.log( "time elapsed2:", Date.now()-now );


( async () => {
    console.log( "time elapsed3:", Date.now()-now );
    const canvasRenderService=new CanvasRenderService( width, height );
    console.log( "time elapsed4:", Date.now()-now );
    const imageBuffer=await canvasRenderService.renderToBuffer( configuration );
    console.log( "time elapsed5:", Date.now()-now );
    fs.writeFileSync( "./filePhotto.png", imageBuffer );
    console.log( "time elapsed6:", Date.now()-now );
    console.log( 'reaching' );
    console.log( "time elapsed7:", Date.now()-now );
} )();

console.log( "time elapsed8:", Date.now()-now );

这是这个的输出:

time elapsed0: 0
time elapsed1: 39
time elapsed2: 39
time elapsed3: 39
time elapsed4: 180
time elapsed8: 33718
time elapsed5: 33752
time elapsed6: 33767
reaching
time elapsed7: 33767

当我使用 CDN 在前端渲染时,它只需要 100。

我真的很感激每一个帮助和建议。

标签: javascriptnode.jscanvaschart.js

解决方案


推荐阅读