在Node.js上使用画布的条形图png图像面临的问题

我是node.js和chart.js库的新手。目前,我正在尝试通过在节点上使用Chart.js在png图像中制作条形图。我可以在节点上制作条形图,但是图像质量不好,并且轴上的标签过于模糊。

注意:当我使用相同的chart.js配置在浏览器上制作图表时,那么我得到了完美的图表而没有任何模糊问题。

参考下图:

Bar chart Image

要运行代码,请执行以下步骤:

  1. Make sure you have node installed on your server
  2. make server.js and copy below server.js code
  3. make package.json in same folder and copy below package.json code
  4. run npm install in terminal
  5. after installations over , run node server in terminal
  6. step 4 will create a file serverBar.png which contain graph .

server.js


var Chart = require('chart.js');
var jsdom = require("jsdom");

const { createCanvas, loadImage } = require('canvas')
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = new JSDOM("").window;
global.document = document;
global.window = window;
const canvas = createCanvas(600, 300);

Chart.defaults.global.defaultFontColor = 'red';
 Chart.defaults.global.defaultFontSize = 16;



const ctx = canvas.getContext('2d');


// Data with datasets options
var data = {
    labels: ["Vanilla", "Chocolate", "Strawberry"],
      datasets: [
        {
            label: "Ice Cream Sales ",
            fill: true,
            backgroundColor: [
                'moccasin',
                'saddlebrown',
                'lightpink'],
            data: [11, 9, 4]
        }
    ]
};

// Notice how nested the beginAtZero is
var options = {
    responsive: false,
        title: {
                  display: true,
                  text: 'Ice Cream Truck Report',
                  position: 'bottom'
              },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
};


var myChart =  new Chart(ctx, {
    type: 'bar',
    data: data,
    options: options
});




  var base64Data = myChart.toBase64Image().replace(/^data:image\/png;base64,/, "");

  require("fs").writeFile("serverBar.png", base64Data, 'base64', function(err) {
    console.log(err);
  });



package.json

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "canvas": "^2.6.1",
    "chart.js": "^2.9.3",
    "d3": "^5.16.0",
    "jsdom": "^16.2.2"
  }
}

```


评论