最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert SVG to PNG inside Web Worker - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Apr 19, 2016 at 8:40 Christoph BühlerChristoph Bühler 2,9233 gold badges31 silver badges45 bronze badges 1
  • 1 Perhaps 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: stackoverflow./questions/9853325/… – enhzflep Commented Apr 19, 2016 at 10:30
Add a ment  | 

3 Answers 3

Reset to default 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./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 piled 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

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, position, 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.

Chrome does not intend to support the creation of ImageBitmap in service workers starting from an SVG blob: https://issues.chromium/issues/41250699

If you need to do this in a Web Extension, you can use the chrome.offscreen API and use the DOM as you normally would on a web page.

发布评论

评论列表(0)

  1. 暂无评论