简体   繁体   English

无法从 SVG 创建 bitmap

[英]Cannot create bitmap from SVG

I'm trying to create a bitmap from a SVG file but I'm getting the following error:我正在尝试从 SVG 文件创建 bitmap,但出现以下错误:

Uncaught (in promise) DOMException: The source image could not be decoded.

I'm using the following code:我正在使用以下代码:

const response = await fetch(MARKER_PATH);
const svgStr = await response.text();
const svgBlob = new Blob([svgStr], { type: 'image/svg+xml' });
this.marker = await createImageBitmap(svgBlob);

The marker code can be found at this link .标记代码可在此链接中找到。 The SVG is valid (or so I think). SVG 是有效的(我认为是这样)。 I can see it correctly and if I draw it how an image on a canvas, then it works perfectly so I do not why it's failing.我可以正确地看到它,如果我将它绘制为 canvas 上的图像,那么它可以完美地工作,所以我不知道为什么它会失败。

I have thought that maybe it has to do with the encoding, but that does not make sense either because the SVG can be loaded correctly in other environments.我认为这可能与编码有关,但这也没有意义,因为 SVG 可以在其他环境中正确加载。 Any idea what's going on?知道发生了什么事吗?

Currently no browser does support creating an ImageBitmap from a Blob that holds an SVG document, while per specs they should.目前没有浏览器支持从包含 SVG 文档的 Blob 创建 ImageBitmap,但根据规范他们应该支持。
I wrote a monkey-patch that does fill this hole (and others) that you can use:我写了一个 monkey-patch来填补你可以使用的这个洞(和其他洞):

 fetch("https://gist.githubusercontent.com/antoniogamiz/d1bf0b12fb2698d1b96248d410bb4219/raw/b76455e193281687bb8355dd9400d17565276000/marker.svg").then( r => r.blob() ).then( createImageBitmap ).then( console.log ).catch( console.error );
 <script src="https://cdn.jsdelivr.net/gh/Kaiido/createImageBitmap/dist/createImageBitmap.js"></script>

Basically, for this case, I perform a first (async) test using a dummy Blob that should work, and if it detects that the UA doesn't support this feature, Blobs input with a type: "image/svg+xml" are converted to an HTMLImageElement that points to a blob:// URI to the Blob.基本上,对于这种情况,我使用应该工作的虚拟 Blob 执行第一次(异步)测试,如果它检测到 UA 不支持此功能,则type: "image/svg+xml"的 Blob 输入是转换为指向 Blob:// URI 的HTMLImageElement
This means that this fix does not work in Workers .这意味着此修复程序在 Workers 中不起作用

Also note that per specs only SVG images with an intrinsic width and height (ie an absolute width and height attributes) are supported by this method.另请注意,根据规范,此方法仅支持 SVG 具有固有宽度和高度(即绝对widthheight属性)的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM