forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart-export.ts
More file actions
49 lines (41 loc) 路 1.35 KB
/
Copy pathchart-export.ts
File metadata and controls
49 lines (41 loc) 路 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import html2canvas from 'html2canvas';
export type ExportBackground = 'white' | 'transparent';
function buildFilename(title: string) {
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
const date = new Date().toISOString().slice(0, 10);
return `${slug}-${date}.png`;
}
async function captureElement(element: HTMLElement, background: ExportBackground) {
return html2canvas(element, {
scale: 2,
backgroundColor: background === 'transparent' ? null : '#ffffff',
useCORS: true,
logging: false,
});
}
export async function downloadChartImage(
title: string,
element: HTMLElement,
background: ExportBackground,
) {
const canvas = await captureElement(element, background);
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = buildFilename(title);
link.click();
}
export async function copyChartImage(
element: HTMLElement,
background: ExportBackground,
) {
const canvas = await captureElement(element, background);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/png'));
if (!blob || typeof ClipboardItem === 'undefined') {
throw new Error('Clipboard image copy is not supported in this browser.');
}
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob,
}),
]);
}