使用 react-chartjs-2,如何使用下载按钮将图表保存为 png
using react-chartjs-2 , How can I save my chart as png using a download button
我正在尝试使用按钮 Onclick 下载我的 chart.js 图表作为 png,但我不知道我将如何实现这一点,我已经完成了这个答案 但对我来说还不够清楚,因为我是 chart.js 的新手,不知道如何将这些变量与我的按钮连接起来。
import React from 'react';
import { Component, useRef } from 'react';
import { Bar } from 'react-chartjs-2';
import 'chartjs-plugin-datalabels';
const data = {
labels: ['Finance & Business', 'Mining', 'Community Services', 'Electricity', 'Agriculture', 'Construction', 'Manufacture', "Trade & Tourism", "Transport & Logistics"],
datasets: [
{
label: 'My First dataset',
backgroundColor: ["#3283FC", "", "", "#00C0C8", "#C0BD00", "#3A46B1", "#00A150", "#FEB200", "#9302a1"],
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [0.6, 0.0, 0.0, -0.1, -0.1, -0.3, -0.3, -0.6, -1.0],
}
]
};
class StackedBar extends Component {
render() {
return (
<div>
<h2>Bar Example (custom size)</h2>
<Bar
data={data}
options={{
plugins: {
datalabels: {
display: true,
color: '#fff'
}
},
title: {
display: true,
text: 'Contribution Percentage',
position: 'left'
},
maintainAspectRatio: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
borderDash: [2, 6],
color: "black"
},
scales: {
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
steps: 0.5,
stepSize: 0.5,
max: 1.5,
min: -1.0
},
}]
},
}}
/>
</div>
);
}
}
export default StackedBar;
所以我安装了一个名为 FileSave.js 的插件 //
- npm 安装
npm i file-saver
- 导入插件
import { saveAs } from 'file-saver';
- 不仅仅是写这个 blob 函数
class StackedBar extends Component {
saveCanvas() {
//save to png
const canvasSave = document.getElementById('stackD');
canvasSave.toBlob(function (blob) {
saveAs(blob, "testing.png")
})
}
render() {
return (
<div>
<a onClick={this.saveCanvas}>Download as PNG</a>
<Bar id="stackD" data={data} options={options} />
</div>
);
}
}
export default StackedBar;
另一种选择是使用图表引用,然后使用 chart.js toBase64Image 函数。将其保存为 base64,转换为 blob 并使用文件保护程序包另存为文件。
import { saveAs } from 'file-saver';
/**
* @param b64Data
* @param contentType
* @param sliceSize
* @returns {Blob}
* @link
*/
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < slice.length; i += 1) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: contentType });
};
... in component
const chartRef = useRef(null);
... in jsx...
<Button
onClick={() => {
const b64 = chartRef.current.toBase64Image().replace('data:image/png;base64,', '');
const content = b64toBlob(b64);
const file = new File([content], 'Revenue_chart.png', { type: 'image/png' });
saveAs(file);
}}
>
img
</Button>
<Line data={data} options={options} ref={chartRef} />
我正在尝试使用按钮 Onclick 下载我的 chart.js 图表作为 png,但我不知道我将如何实现这一点,我已经完成了这个答案
import React from 'react';
import { Component, useRef } from 'react';
import { Bar } from 'react-chartjs-2';
import 'chartjs-plugin-datalabels';
const data = {
labels: ['Finance & Business', 'Mining', 'Community Services', 'Electricity', 'Agriculture', 'Construction', 'Manufacture', "Trade & Tourism", "Transport & Logistics"],
datasets: [
{
label: 'My First dataset',
backgroundColor: ["#3283FC", "", "", "#00C0C8", "#C0BD00", "#3A46B1", "#00A150", "#FEB200", "#9302a1"],
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [0.6, 0.0, 0.0, -0.1, -0.1, -0.3, -0.3, -0.6, -1.0],
}
]
};
class StackedBar extends Component {
render() {
return (
<div>
<h2>Bar Example (custom size)</h2>
<Bar
data={data}
options={{
plugins: {
datalabels: {
display: true,
color: '#fff'
}
},
title: {
display: true,
text: 'Contribution Percentage',
position: 'left'
},
maintainAspectRatio: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
borderDash: [2, 6],
color: "black"
},
scales: {
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
steps: 0.5,
stepSize: 0.5,
max: 1.5,
min: -1.0
},
}]
},
}}
/>
</div>
);
}
}
export default StackedBar;
所以我安装了一个名为 FileSave.js 的插件 //
- npm 安装
npm i file-saver
- 导入插件
import { saveAs } from 'file-saver';
- 不仅仅是写这个 blob 函数
class StackedBar extends Component {
saveCanvas() {
//save to png
const canvasSave = document.getElementById('stackD');
canvasSave.toBlob(function (blob) {
saveAs(blob, "testing.png")
})
}
render() {
return (
<div>
<a onClick={this.saveCanvas}>Download as PNG</a>
<Bar id="stackD" data={data} options={options} />
</div>
);
}
}
export default StackedBar;
另一种选择是使用图表引用,然后使用 chart.js toBase64Image 函数。将其保存为 base64,转换为 blob 并使用文件保护程序包另存为文件。
import { saveAs } from 'file-saver';
/**
* @param b64Data
* @param contentType
* @param sliceSize
* @returns {Blob}
* @link
*/
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < slice.length; i += 1) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: contentType });
};
... in component
const chartRef = useRef(null);
... in jsx...
<Button
onClick={() => {
const b64 = chartRef.current.toBase64Image().replace('data:image/png;base64,', '');
const content = b64toBlob(b64);
const file = new File([content], 'Revenue_chart.png', { type: 'image/png' });
saveAs(file);
}}
>
img
</Button>
<Line data={data} options={options} ref={chartRef} />