使用.toDataUrl()将Chart.js画布图表转换为图像会导致空白图像

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

本文关键字:图像 转换 空白 布图表 toDataUrl js Chart 使用      更新时间:2023-10-16

我使用的是Chart.js。我试图通过获取一个64进制字符串将图表转换为图像。教程(http://www.chartjs.org/docs/)用整整一行的篇幅讨论这个主题:

canvas元素还允许将内容保存为基64字符串,允许将图表保存为图像。

canvas元素具有toDataURL的方法,该方法返回图像的base64字符串。然而,当我这样做时,它渲染的图像只是一个具有图表尺寸的透明矩形,并且它不包括图表内容。

这是一把小提琴:http://jsfiddle.net/KSgV7/

小提琴中的"图像"是用黑色边框设计的,所以你可以看到它们应该在哪里,因为它们似乎只是一个大的透明块。

有人成功地将Chart.js图表转换为图像吗?

图表似乎是异步的,因此您可能需要在动画完成时提供回调,否则画布将为空。

var options = {
    bezierCurve : false,
    onAnimationComplete: done  /// calls function done() {} at end
};

Chart.JS API在发布后发生了变化,旧的示例似乎对我不起作用。这是一个更新的小提琴,适用于新版本的

HTML:

<body>
    <canvas id="canvas" height="450" width="600"></canvas>
    <img id="url" />
</body>

JS:

function done(){
  alert("haha");
  var url=myLine.toBase64Image();
  document.getElementById("url").src=url;
}
var options = {
  bezierCurve : false,
  animation: {
    onComplete: done
  }
};
var myLine = new 
   Chart(document.getElementById("canvas").getContext("2d"),
     {
        data:lineChartData,
        type:"line",
        options:options
      }
    );

http://jsfiddle.net/KSgV7/585/

首先将Chart.js画布转换为base64字符串。

var url_base64 = document.getElementById('myChart').toDataURL('image/png');

将其设置为锚点标记的href属性。

link.href = url_base64;

<a id='link' download='filename.png'>Save as Image</a>

您应该使用Chartjs API函数toBase64Image(),并在动画完成后调用它。因此:

var pieChart, URI;
var options = {
    animation : {
        onComplete : function(){    
            URI = pieChart.toBase64Image();
        }
    }
};
var content = {
    type: 'pie', //whatever, not relevant for this example
    data: {
        datasets: dataset //whatever, not relevant for this example
    },
    options: options        
};    
pieChart = new Chart(pieChart, content);

示例

你可以检查这个例子并运行它

var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart
      // create 12 datasets, since we have 12 items
      // data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')
      // put 0, if there is no data for the particular bar
      datasets: [{
         label: 'Washing and cleaning',
         data: [0, 8],
         backgroundColor: '#22aa99'
      }, {
         label: 'Traffic tickets',
         data: [0, 2],
         backgroundColor: '#994499'
      }, {
         label: 'Tolls',
         data: [0, 1],
         backgroundColor: '#316395'
      }, {
         label: 'Parking',
         data: [5, 2],
         backgroundColor: '#b82e2e'
      }, {
         label: 'Car tax',
         data: [0, 1],
         backgroundColor: '#66aa00'
      }, {
         label: 'Repairs and improvements',
         data: [0, 2],
         backgroundColor: '#dd4477'
      }, {
         label: 'Maintenance',
         data: [6, 1],
         backgroundColor: '#0099c6'
      }, {
         label: 'Inspection',
         data: [0, 2],
         backgroundColor: '#990099'
      }, {
         label: 'Loan interest',
         data: [0, 3],
         backgroundColor: '#109618'
      }, {
         label: 'Depreciation of the vehicle',
         data: [0, 2],
         backgroundColor: '#109618'
      }, {
         label: 'Fuel',
         data: [0, 1],
         backgroundColor: '#dc3912'
      }, {
         label: 'Insurance and Breakdown cover',
         data: [4, 0],
         backgroundColor: '#3366cc'
      }]
   },
   options: {
      responsive: false,
      legend: {
         position: 'right' // place legend on the right side of chart
      },
      scales: {
         xAxes: [{
            stacked: true // this should be set to make the bars stacked
         }],
         yAxes: [{
            stacked: true // this also..
         }]
      },
      animation : {
         onComplete : done
      }      
   }
});
function done(){
    alert(chart.toBase64Image());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" width="700"></canvas>

您可以使用plugins访问afterRender挂钩。

以下是所有可用的插件api。

在html文件中:

<html>
  <canvas id="myChart"></canvas>
  <div id="imgWrap"></div>
</html>

在js文件中:

var chart = new Chart(ctx, {
  ...,
  plugins: [{
    afterRender: function () {
      // Do anything you want
      renderIntoImage()
    },
  }],
  ...,
});
const renderIntoImage = () => {
  const canvas = document.getElementById('myChart')
  const imgWrap = document.getElementById('imgWrap')
  var img = new Image();
  img.src = canvas.toDataURL()
  imgWrap.appendChild(img)
  canvas.style.display = 'none'
}

您也可以使用toBase64Image()方法设置动画:false

var options = {
    bezierCurve : false,
    animation: false
};

更新的Fiddle

@EH_warch您需要使用Complete回调来生成base64:

onAnimationComplete: function(){
    console.log(this.toBase64Image())
}

如果看到白色图像,则表示在完成渲染之前调用了toBase64Image。