如何使用toBase64Image导出chart .js图表,但没有透明度?



我的应用程序中有几个图表,使用Chart.js库创建。我需要导出它们,并包含在应用程序生成的某种报告中。下面附加了一个示例图表代码:

export default {
extends: Line,
mixins: [reactiveProp],
data() {
return {
options: {
maintainAspectRatio: false,
responsive: true,
legend: {
display: true,
position: 'bottom',
},
scales: {
yAxes: [
{
ticks: {
suggestedMin: 0,
callback(tick) {
return `${tick}%`;
},
},
},
],
},
tooltips: {
callbacks: {
label(tooltipItem, data) {
const dataset = data.datasets[tooltipItem.datasetIndex];
const currentValue = dataset.data[tooltipItem.index];
return ` ${dataset.label}: ${currentValue}%`;
},
},
},
animation: {
// eslint-disable-next-line no-unused-vars
onComplete(animation) {
store.commit('myModule/myMutation', this.toBase64Image());
},
},
},
};
},
mounted() {
this.renderChart(this.chartData, this.options);
},
};

正如你所注意到的,我使用onComplete将图表保存在我的商店中。我在那里调用函数toBase64Image()。图像被正确保存,但是背景被忽略,所以结果是透明的。我想有图表,但与白色背景后,序列化。有可能实现吗?我怎么能解决这个问题(我曾试图设置背景颜色使用图表样式,但仍然序列化结果是透明的)?谢谢你的帮助

出现这种行为是因为没有在图表上绘制任何背景。这可以通过一个自定义的内联插件来修复,像这样(fillStyle是背景的颜色):

plugins: [{
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chart.canvas.width, chart.canvas.height);
ctx.restore();
}
}]

的例子:

var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
},
plugins: [{
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chart.canvas.width, chart.canvas.height);
ctx.restore();
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

最新更新