使用.toDataUrl()将Chart.js画布图转换为图像会生成空白图像

时间:2013-11-26 00:03:00

标签: javascript html5 canvas chart.js

我正在使用Chart.js。我试图通过获取基本64字符串将图表转换为图像。教程(http://www.chartjs.org/docs/)在主题上使用了整整一行:

  

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

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

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

小提琴中的“图像”采用黑色边框设计,因此您可以看到它们应该在哪里,因为它们看起来只是一个很大的透明块。

有没有人成功将Chart.js图表​​转换为图片?

8 个答案:

答案 0 :(得分:26)

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

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

答案 1 :(得分:13)

自从发布以来,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/

答案 2 :(得分:6)

首先将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>

答案 3 :(得分:2)

您应该使用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);

实施例

您可以查看此示例并运行它

&#13;
&#13;
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());
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" width="700"></canvas>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您可以使用afterRender访问plugins。{/ p>

而且here都是可用的插件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'
}

答案 5 :(得分:-1)

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

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

Updated Fiddle

答案 6 :(得分:-1)

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

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

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

答案 7 :(得分:-2)

我使用Chartjs.js库在此代码中解决了此问题

HTML代码:

<img id="ChartImage" style="margin: 0 auto;" />
<canvas id="myChart" style="margin: 0 auto;" ></canvas>

JavaScript图表选项:

options: {
  legend: { position: 'bottom', display: true },
  animation: {
     onComplete: function(){
        var url = barChart.toBase64Image(); //get image as base64
        document.getElementById("ChartImage").src = url; //to fill image in html
     }
  }    
},