将chart.js导出为image

tyky79it  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(158)

我的图表生成函数如下:

createChart(db_data: string[], count: number[]) {
    const chartOptions = {
      type: 'horizontalBar',
      data: {
        labels: db_data,
        datasets: [
          {
            label: 'Chart',
            data: count,
            borderColor: '#99f0d1',
            backgroundColor: '#60b3a1',
            borderWidth: 0.1,
          },
          
        ],
      },
      onAnimationComplete: function()
      {
          this.showTooltip(this.datasets[0].data, true);
      },
      options: {
...

    this.chartElement = document.getElementById('canvas');
    this.chart = new Chart(this.chartElement, chartOptions);

我想导出为图像(PNG),但诀窍是,我想修改背景和酒吧的颜色。我的导出功能运行良好,但我不能设置修改后的背景属性。

exportChart() {
  const currentDate = new Date().toISOString().slice(0, 10);
  
  
  const canvas = this.chart.canvas;

  console.log(canvas);
  canvas.style.backgroundColor = 'blue';

  const chartDataURL = this.chart.toBase64Image();

  
  canvas.style.backgroundColor = 'blue'; 

  const link = document.createElement('a');
  link.href = chartDataURL;
  link.download = `statistic_${currentDate}.png`;
  link.click();
}

我试图修改图表生成(与ctx)

sq1bmfud

sq1bmfud1#

documentation中所述,如果您想下载带有背景颜色的图表,则需要使用自定义插件:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      customCanvasBackgroundColor: {
        color: 'pink'
      }
    }
  },
  plugins: [{
    id: 'customCanvasBackgroundColor',
    beforeDraw: (chart, args, options) => {
      const {
        ctx
      } = chart;
      ctx.save();
      ctx.globalCompositeOperation = 'destination-over';
      ctx.fillStyle = options.color || '#99ffff';
      ctx.fillRect(0, 0, chart.width, chart.height);
      ctx.restore();
    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
</body>

相关问题