$("#NoBidsChart").get(0).toBlob(function(value) {
saveAs(value, "Summary.jpg");
});
我正在使用Chart JS(v2.5.0)来渲染图表。当我尝试使用Canvas to Blob转换器和filesaver.js导出图表时,背景会变成黑色。那么我该如何获得带有自定义背景颜色(最好是白色)的图像呢?
$("#NoBidsChart").get(0).toBlob(function(value) {
saveAs(value, "Summary.jpg");
});
我正在使用Chart JS(v2.5.0)来渲染图表。当我尝试使用Canvas to Blob转换器和filesaver.js导出图表时,背景会变成黑色。那么我该如何获得带有自定义背景颜色(最好是白色)的图像呢?
如果你想要自定义背景色,那么你需要用自己喜欢的颜色绘制一个背景,具体方法如下...
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>
正如我在接受的答案评论中所述,beforeDraw
事件使得fillRect
代码被多次调用(据我所见,每个数据点一次)让我感到不安。
但是,我无法通过在任何其他事件上调用来使该方法生效。 然而,我刚刚采用了此答案中描述的编码方法,并将其插入到在afterRender
事件上注册的代码中,它确实做到了我想要的:只运行一次并保留白色背景。
Chart.plugins.register({
afterRender: function(c) {
console.log("afterRender called");
var ctx = c.chart.ctx;
ctx.save();
// This line is apparently essential to getting the
// fill to go behind the drawn graph, not on top of it.
// Technique is taken from:
// https://dev59.com/h6vka4cB1Zd3GeqPmgSX#50126796
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, c.chart.width, c.chart.height);
ctx.restore();
}
});
请访问(并投票支持)另一个已发布问题的相关答案。const plugin = {
beforeDraw: (chartCtx) => {
const ctx = chartCtx.canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chartCtx.width, chartCtx.height);
ctx.restore();
}
};
然后将插件添加到图表中:
<Line ref={chartRef} data={chartData} options={options} plugins={[plugin]} />
我创建了一个函数,使用toBase64Image函数提取图像。我将此函数附加到按钮上,以便在单击按钮时下载图表图像。
function downloadImage(){
const link = document.createElement("a");
link.download = `${chart.name || 'chart'}.jpg`
link.href = chartRef.current.toBase64Image('image/jpeg', 1);
link.click();
}
toBlob
方法在 Safari 中不受支持。虽然它在 Firefox 中可以工作。 - ɢʀᴜɴᴛ