1
1
import { Canvg , RenderingContext2D , presets } from "canvg" ;
2
2
3
+ const offscreenPreset = presets . offscreen ( ) ;
3
4
export async function svgToBlob (
4
5
width : number ,
5
6
height : number ,
@@ -20,24 +21,29 @@ export async function svgToBlob(
20
21
if ( ! ctx ) {
21
22
throw new Error ( "No canvas context" ) ;
22
23
}
23
- const v = await Canvg . fromString (
24
- ctx as RenderingContext2D ,
25
- svgString ,
26
- presets . offscreen ( )
27
- ) ;
24
+ const v = Canvg . fromString ( ctx as RenderingContext2D , svgString , {
25
+ ...offscreenPreset ,
26
+ // Overwrite the Canvg typescript types here, replace once this Canvg ticket is resolved:
27
+ // https://github.com/canvg/canvg/issues/1754
28
+ createCanvas : offscreenPreset . createCanvas as ( ) => OffscreenCanvas & {
29
+ getContext ( contextId : "2d" ) : OffscreenCanvasRenderingContext2D ;
30
+ } ,
31
+ } ) ;
28
32
29
33
// Render only first frame, ignoring animations and mouse.
30
34
await v . render ( ) ;
31
35
32
36
let blob ;
33
37
if ( "OffscreenCanvas" in window ) {
34
- blob = await ( canvas as OffscreenCanvas ) . convertToBlob ( {
38
+ canvas = canvas as OffscreenCanvas ;
39
+ blob = await canvas . convertToBlob ( {
35
40
type : encodeType ,
36
41
} ) ;
37
42
} else {
38
43
blob = await new Promise < Blob | null > ( ( done , err ) => {
39
44
try {
40
- ( canvas as HTMLCanvasElement ) . toBlob ( done , encodeType ) ;
45
+ canvas = canvas as HTMLCanvasElement ;
46
+ canvas . toBlob ( done , encodeType ) ;
41
47
} catch ( error ) {
42
48
err ( error ) ;
43
49
}
0 commit comments