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.
Asked
Active
Viewed 1,285 times
9
-
1Perhaps you can leverage Inkscape or ImageMagick? (I've not had occasion to play with web-workers) Provided you get a full-calorie executable environment, you can use either of the two above sugestions. For more, see: http://stackoverflow.com/questions/9853325/how-to-convert-a-svg-to-a-png-with-image-magick – enhzflep Apr 19 '16 at 10:30
2 Answers
3
Weeell, you can always manually parse the SVG and build a bitmap from that, but (!) it's a tad more work obviously as you'd have to build a SVG parser as well as a PNG writer, not to mention rasterizing code for lines and two-modes polygon fill incl. anti-aliasing, pattern, matrix, composition, blending and gradient support. Could be a nice weekend project though :)
On a more serious note though: you can only do this with the built-in tools using regular context (none-webworker) or optionally set up a server based service.
-
1Thank you for the answer. I am setting up a web service. It just would have been a smoother solution to do the conversion directly on a second thread, because I will be drawing the exact same SVG in various scales. – Christoph Bühler Apr 19 '16 at 11:18
-
1@ChristophBühler why do you need the png version ? svg does scale pretty well ;-) (even on canvas) – Kaiido Apr 19 '16 at 11:51
-
1@Kaiido The SVGs are quite huge (20mb) and the images have to appear quickly. This is why I write a canvas buffer. – Christoph Bühler Apr 19 '16 at 12:02
-
1ouch! a 20mb svg oO. But once loaded into an `
` you should still be able to draw it as fast as a any one, at any scale on a canvas. – Kaiido Apr 19 '16 at 12:06
-
Yeah, that's correct. However, the process of putting an SVG onto an Image is crazy expensive.. I will test a few things and let you know! – Christoph Bühler Apr 19 '16 at 13:30
2
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
PS: I'm the author of thumbo

Victor Aremu
- 73
- 1
- 5