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

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

I am using Chart.js. I am trying to convert the chart to an image by getting a base 64 string. The tutorial (http://www.chartjs.org/docs/) devotes an entire 1 line on the topic:

The canvas element also allows for saving the contents as a base 64 string, allowing saving the chart as an image.

A canvas element has the method of toDataURL, which returns a base64 string of the image. However, when I do that, the image it renders is just a transparent rectangle with the dimensions of the chart, and it does not include the chart contents.

Here is a fiddle: http://jsfiddle.net/KSgV7/

The "images" in the fiddle are styled with a black border, so you can see where they are supposed to be, since they seem to just be a big transparent block.

Has anyone successfully converted a Chart.js chart to an image?

回答1:

The chart seem to be async so you will probably need to provide a callback when the animation has finished or else the canvas will be empty.

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


回答2:

Chart.JS API has changed since this was posted and older examples did not seem to be working for me. here is an updated fiddle that works on the newer versions

HTML:

     

JS:

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

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



回答3:

First convert your Chart.js canvas to base64 string.

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

Set it as a href attribute for anchor tag.

link.href = url_base64;

Save as Image



回答4:

You can access afterRender hook by using plugins.

And here are all the plugin api available.

In html file:

   

In js file:

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' } 


回答5:

You can also use the toBase64Image() method setting animation: false

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

Updated Fiddle



回答6:

@EH_warch You need to use the Complete callback to generate your base64:

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

If you see a white image, it means you called the toBase64Image before it finished rendering.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!