3

I am developing a web page that does some fairly heavy processing of SVG string data. Because these strings could get to be m/bs in size I would like to move the rendering of the SVGs (browser dependant) to a worker in order to avoid blocking the UI.

My problem is that no DOM elements are accessible in workers - is there any way to draw the SVG to an OffscreenCanvas's 2D context using the SVG string alone? Or is there a way of converting the string to a data format that can be passed to the worker?

chips
  • 160
  • 1
  • 10

1 Answers1

4

No native way yet.

Per the specs, you should be able to create an ImageBitmap from a Blob holding your SVG image even in a Worker.
In reality, no browser has implemented it, and when I talked about it with the implementers, it seems it's not on anyone's track to do so.

In Chrome you have access to the Path2D constructor, which can somehow help with <path>'s d attributes, but that's really just a very small part of rendering an SVG.

So the best will probably be to use a library for this.
Notabily, I think canvg is the most appropriate here. I don't use it myself but they're here for a long time now, and it seems the latest version does work with OffscreenCanvas in a Worker (in Chrome).

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I thought I was probably pushing the limits of the web a bit. Wasn't aware of canvg - it looks interesting - can't imagine it's particularly fast, but I guess if it's off the main thread that's not a huge deal. Thanks for your help. – chips Nov 23 '21 at 13:07