Home > Software design >  Is there a way to render an SVG string to an OffscreenCanvas in a web worker?
Is there a way to render an SVG string to an OffscreenCanvas in a web worker?

Time:11-24

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?

CodePudding user response:

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).

  • Related