Search code examples
javascriptsvgweb-worker

Convert SVG to PNG inside Web Worker


I would like to convert an SVG to a PNG inside a Web Worker. My problem is, that the DOM is not accessible from within the Worker, so I cannot draw the SVG to a canvas or something like that.


Solution

  • You can use thumbo

    import Thumbo, { Transfer } from "thumbo";
    
    Thumbo.init().then(async () => {
      Thumbo.thumbnail(
        Transfer(await (await fetch("/path/to/img.svg")).arrayBuffer()),
        Thumbo.ImageFormat.Svg,
        20,
        20
      ).then((thumbnailBuffer) => {
        document.getElementById("img1").src = URL.createObjectURL(
          new Blob([thumbnailBuffer])
        );
      });
    
      Thumbo.thumbnailFromUrl(
        "https://example.com/image.svg",
        Thumbo.ImageFormat.Svg,
        20,
        20
      ).then((thumbnailBuffer) => {
        document.getElementById("img2").src = URL.createObjectURL(
          new Blob([thumbnailBuffer])
        );
      });
    });
    

    Under the hood, thumbo uses Rust's tiny_skia & resvg libraries compiled to a Web Assembly module, to render SVG in a web worker and convert it to PNG. See thumbo-core, thumbo

    Demo ▶️ Source code

    PS: I'm the author of thumbo