将chart.js导出为image

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

我的图表生成函数如下:

  1. createChart(db_data: string[], count: number[]) {
  2. const chartOptions = {
  3. type: 'horizontalBar',
  4. data: {
  5. labels: db_data,
  6. datasets: [
  7. {
  8. label: 'Chart',
  9. data: count,
  10. borderColor: '#99f0d1',
  11. backgroundColor: '#60b3a1',
  12. borderWidth: 0.1,
  13. },
  14. ],
  15. },
  16. onAnimationComplete: function()
  17. {
  18. this.showTooltip(this.datasets[0].data, true);
  19. },
  20. options: {
  21. ...
  22. this.chartElement = document.getElementById('canvas');
  23. this.chart = new Chart(this.chartElement, chartOptions);

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

  1. exportChart() {
  2. const currentDate = new Date().toISOString().slice(0, 10);
  3. const canvas = this.chart.canvas;
  4. console.log(canvas);
  5. canvas.style.backgroundColor = 'blue';
  6. const chartDataURL = this.chart.toBase64Image();
  7. canvas.style.backgroundColor = 'blue';
  8. const link = document.createElement('a');
  9. link.href = chartDataURL;
  10. link.download = `statistic_${currentDate}.png`;
  11. link.click();
  12. }

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

sq1bmfud

sq1bmfud1#

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

  1. var options = {
  2. type: 'line',
  3. data: {
  4. labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
  5. datasets: [{
  6. label: '# of Votes',
  7. data: [12, 19, 3, 5, 2, 3],
  8. borderColor: 'pink'
  9. },
  10. {
  11. label: '# of Points',
  12. data: [7, 11, 5, 8, 3, 7],
  13. borderColor: 'orange'
  14. }
  15. ]
  16. },
  17. options: {
  18. plugins: {
  19. customCanvasBackgroundColor: {
  20. color: 'pink'
  21. }
  22. }
  23. },
  24. plugins: [{
  25. id: 'customCanvasBackgroundColor',
  26. beforeDraw: (chart, args, options) => {
  27. const {
  28. ctx
  29. } = chart;
  30. ctx.save();
  31. ctx.globalCompositeOperation = 'destination-over';
  32. ctx.fillStyle = options.color || '#99ffff';
  33. ctx.fillRect(0, 0, chart.width, chart.height);
  34. ctx.restore();
  35. }
  36. }]
  37. }
  38. var ctx = document.getElementById('chartJSContainer').getContext('2d');
  39. new Chart(ctx, options);
  1. <body>
  2. <canvas id="chartJSContainer" width="600" height="400"></canvas>
  3. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
  4. </body>
展开查看全部

相关问题