Cannot create bitmap from SVG

1k Views Asked by At

I'm trying to create a bitmap from a SVG file but I'm getting the following error:

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

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. Any idea what's going on?

1

There are 1 best solutions below

0
On

Currently no browser does support creating an ImageBitmap from a Blob that holds an SVG document, while per specs they should.
I wrote a monkey-patch that does fill this hole (and others) that you can use:

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.
This means that this fix does not work in Workers.

Also note that per specs only SVG images with an intrinsic width and height (i.e an absolute width and height attributes) are supported by this method.