javascript 如何创建图表并将其写入png文件?

llmtgqce  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(119)

你好,我正在尝试使用chart.js创建图表,但我发现很难找到如何在我的node js程序中创建图表,它需要一个上下文,但由于它是本地的,我不知道在这里放什么,因为它不意味着是一个网站,它也不会是。
我想创建一个图表,并把它作为一个png有办法做到这一点吗?
我试过了

const { Chart } = require("chart.js/auto");
let ctx = null
let crt = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        labels: [1, 2, 3, 4, 5],
        datasets: [{
            label: 'data',
            data: [[-3, 5], [2, 10], [1, 3], [-4, -1], [4, 8]],
            backgroundColor: 'lightblue'
        }]
    },
    options: {
        responsive: true,
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Horizontal Floating Bars'
        }
    }
});```

But have not had any results from this as I got an error. Can someone please help me?
gorkyyrv

gorkyyrv1#

js的工作确实需要一个画布,幸运的是,有一些项目可以在node中提供虚拟画布。也可参见此blog post
设置背景颜色有点棘手,但chart.js docs为我们提供了一个解决方案。
因此,在npm安装canvas之后(您已经安装了chart.js),您的代码可以转换为:

const { Chart } = require("chart.js/auto");

//from https://blog.logrocket.com/creating-saving-images-node-canvas/
const { createCanvas } = require("canvas");
const fs = require("fs");

const width = 1200, height = 800;

const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");

// not working
// ctx.fillStyle = "#ffffff";
// ctx.fillRect(0, 0, canvas.width, canv\as.height);

// from https://www.chartjs.org/docs/latest/configuration/canvas-background.html
const plugin = {
    id: 'customCanvasBackgroundImage',
    beforeDraw: (chart) => {
        const ctx = chart.ctx;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
};

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [1, 2, 3, 4, 5],
        datasets: [{
            label: 'data',
            data: [[-3, 5], [2, 10], [1, 3], [-4, -1], [4, 8]],
            backgroundColor: 'lightblue'
        }]
    },
    options: {
        indexAxis: 'y',
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Horizontal Floating Bars'
        }
    },
    plugins: [plugin]
});

const buffer = canvas.toBuffer("image/png");
fs.writeFileSync("./image.png", buffer);

相关问题