@@ -31,6 +31,58 @@ export const imageTypeOptions: SegmentedProps['options'] = [
31
31
} ,
32
32
] ;
33
33
34
+ export const getImageUrl = async ( {
35
+ imageType,
36
+ id = '#preview' ,
37
+ width,
38
+ } : {
39
+ id ?: string ;
40
+ imageType : ImageType ;
41
+ width ?: number ;
42
+ } ) => {
43
+ let screenshotFn : any ;
44
+ switch ( imageType ) {
45
+ case ImageType . JPG : {
46
+ screenshotFn = domToJpeg ;
47
+ break ;
48
+ }
49
+ case ImageType . PNG : {
50
+ screenshotFn = domToPng ;
51
+ break ;
52
+ }
53
+ case ImageType . SVG : {
54
+ screenshotFn = domToSvg ;
55
+ break ;
56
+ }
57
+ case ImageType . WEBP : {
58
+ screenshotFn = domToWebp ;
59
+ break ;
60
+ }
61
+ }
62
+
63
+ const dom : HTMLDivElement = document . querySelector ( id ) as HTMLDivElement ;
64
+ let copy : HTMLDivElement = dom ;
65
+
66
+ if ( width ) {
67
+ copy = dom . cloneNode ( true ) as HTMLDivElement ;
68
+ copy . style . width = `${ width } px` ;
69
+ document . body . append ( copy ) ;
70
+ }
71
+
72
+ const dataUrl = await screenshotFn ( width ? copy : dom , {
73
+ features : {
74
+ // 不启用移除控制符,否则会导致 safari emoji 报错
75
+ removeControlCharacter : false ,
76
+ } ,
77
+ scale : 2 ,
78
+ width,
79
+ } ) ;
80
+
81
+ if ( width && copy ) copy ?. remove ( ) ;
82
+
83
+ return dataUrl ;
84
+ } ;
85
+
34
86
export const useScreenshot = ( {
35
87
imageType,
36
88
title = 'share' ,
@@ -47,46 +99,7 @@ export const useScreenshot = ({
47
99
const handleDownload = useCallback ( async ( ) => {
48
100
setLoading ( true ) ;
49
101
try {
50
- let screenshotFn : any ;
51
- switch ( imageType ) {
52
- case ImageType . JPG : {
53
- screenshotFn = domToJpeg ;
54
- break ;
55
- }
56
- case ImageType . PNG : {
57
- screenshotFn = domToPng ;
58
- break ;
59
- }
60
- case ImageType . SVG : {
61
- screenshotFn = domToSvg ;
62
- break ;
63
- }
64
- case ImageType . WEBP : {
65
- screenshotFn = domToWebp ;
66
- break ;
67
- }
68
- }
69
-
70
- const dom : HTMLDivElement = document . querySelector ( id ) as HTMLDivElement ;
71
- let copy : HTMLDivElement = dom ;
72
-
73
- if ( width ) {
74
- copy = dom . cloneNode ( true ) as HTMLDivElement ;
75
- copy . style . width = `${ width } px` ;
76
- document . body . append ( copy ) ;
77
- }
78
-
79
- const dataUrl = await screenshotFn ( width ? copy : dom , {
80
- features : {
81
- // 不启用移除控制符,否则会导致 safari emoji 报错
82
- removeControlCharacter : false ,
83
- } ,
84
- scale : 2 ,
85
- width,
86
- } ) ;
87
-
88
- if ( width && copy ) copy ?. remove ( ) ;
89
-
102
+ const dataUrl = await getImageUrl ( { id, imageType, width } ) ;
90
103
const link = document . createElement ( 'a' ) ;
91
104
link . download = `${ BRANDING_NAME } _${ title } _${ dayjs ( ) . format ( 'YYYY-MM-DD' ) } .${ imageType } ` ;
92
105
link . href = dataUrl ;
0 commit comments