1

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?

Kaiido
  • 123,334
  • 13
  • 219
  • 285
Antonio Gamiz Delgado
  • 1,871
  • 1
  • 12
  • 33
  • 1
    there are some rather unusual characters in some of the id values. – Robert Longson Sep 24 '21 at 12:30
  • The error you get is because if the strange characters in the ids. Besides that I'm struggling to get `createImageBitmap()` to work with a SVG even though it should be possible, as I read [createImageBitmap() - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/CreateImageBitmap). – chrwahl Sep 26 '21 at 11:29

1 Answers1

1

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.

Kaiido
  • 123,334
  • 13
  • 219
  • 285