Charts.js呈现轴,但不呈现数据集

hzbexzde  于 2023-01-13  发布在  Chart.js
关注(0)|答案(1)|浏览(143)

我尝试在AWS Lambda函数上使用Charts.js来创建图表图像(png)。
但是,由于某种原因,它绘制了轴,但没有数据。
这是我的代码:

export const plotData = (values: number[]): Buffer | null => {
  const canvas = createCanvas(800, 600);
  let ctx: ChartItem = canvas as unknown as ChartItem;

  const plugin: Plugin = {
    id: "customCanvasBackgroundColor",
    beforeDraw: (chart: any, _args: any, options: any) => {
      const { ctx: context } = chart;
      context.save();
      context.globalCompositeOperation = "destination-over";
      context.fillStyle = options.color || "#99ffff";
      context.fillRect(0, 0, chart.width, chart.height);
      context.restore();
    },
  };

  const chart = new Chart(ctx, {
    type: "line",
    data: {
      datasets: [
        {
          label: "ph",
          data: values.map((y) => ({
            y,
            t: new Date(),
          })),
          borderWidth: 2,
          borderColor: "red",
          backgroundColor: "rgb(255, 0, 0, 0.5)",
        },
      ],
    },
    options: {
      responsive: false,
      animation: false,
      scales: {
        y: {
          beginAtZero: true,
        },
      },
      plugins: {
        legend: {
          position: "top",
        },
        title: {
          display: true,
          text: "TEstuibg",
        },
        customCanvasBackgroundColor: {
          color: "rgba(255,255,255, 1)",
        },
      },
    },
    plugins: [plugin],
  });

  // chart.draw();
  chart.update();

  return canvas.toBuffer("image/png");
};

这就是我调用plotData([100, 200, 300, 400, 500, 1600])时它所呈现的结果:

我已经禁用了动画和响应。是否需要执行其他操作?

2hh7jdfx

2hh7jdfx1#

我会在onComplete事件上创建图像,而不是所有内容都应该可见,至少这在浏览器中有效。
来自文档:"...动画配置提供了回调,这对于将外部绘制与图表动画同步非常有用....",但肯定适用于您的图像创建过程。link to documentation

...
options: {
  animation:{
        duration: 0, // "no" animation 
        onComplete: () => { 
            ...
            // create image
            ... 
        }
    }
}
...

**当然:**在这种情况下,当onComplete事件触发时,您的函数plotData必须是 async 或传递 * 回调函数 *。

相关问题