如何使用 blob 和文件保护程序将 Chart JS 图表保存为没有黑色背景的图像? [英] How to save Chart JS charts as image without black background using blobs and filesaver?
本文介绍了如何使用 blob 和文件保护程序将 Chart JS 图表保存为没有黑色背景的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$("#NoBidsChart").get(0).toBlob(function(value) {
saveAs(value, "Summary.jpg");
});
这里我使用 Chart JS(v2.5.0) 来渲染图表.当我尝试使用 Canvas to Blob 转换器和 filesaver.js 导出图表时,我得到黑色背景.那么如何获得具有自定义背景颜色(最好是白色)的图像?
Here i am using Chart JS(v2.5.0) for rendering charts. When i try to export the charts using Canvas to Blob converter and filesaver.js, i get the black background. So how do i get the image with customized background color(preferably white)?
推荐答案
如果你想要自定义背景颜色,那么你必须用你喜欢的颜色绘制背景,你可以这样做,像这样......
If you want a customized background color then, you'd have to draw a background with your preferred color, and you can do so, like this ...
var backgroundColor = 'white';
Chart.plugins.register({
beforeDraw: function(c) {
var ctx = c.chart.ctx;
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, c.chart.width, c.chart.height);
}
});
<小时>
演示
// draw background
var backgroundColor = 'white';
Chart.plugins.register({
beforeDraw: function(c) {
var ctx = c.chart.ctx;
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, c.chart.width, c.chart.height);
}
});
// chart
var canvas = $('#NoBidsChart').get(0);
var myChart = new Chart(canvas, {
type: 'line',
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: 'Line Chart',
data: [1, 2, 3, 4, 5],
backgroundColor: 'rgba(255, 0, 0, 0.2)',
borderColor: 'rgba(255, 0, 0, 0.5)',
pointBackgroundColor: 'black'
}]
}
});
// save as image
$('#save').click(function() {
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button id="save">Save</button>
<canvas id="NoBidsChart"></canvas>
这篇关于如何使用 blob 和文件保护程序将 Chart JS 图表保存为没有黑色背景的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文