Base64 SVG Images

I cannot get the base64 and SVG database URI to display as an image.

I tried <img>

and <canvas>

, and no one gets SVG.

var url = 'data:image/svg+xml;base64,' + btoa('<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"/></svg>');

document.getElementById('image').src = url;

var context = document.getElementById('canvas').getContext('2d');
var image = new Image();
image.src = url;
context.drawImage(image, 0, 0);
      

canvas, img {
    border: 1px solid black;
}
      

<img id="image" width="200" height="200">

<canvas id="canvas" width="200" height="200"></canvas>
      

Run code


Tested on Chrome and Firefox.

What does SVG not show?

+3


source to share


1 answer


When embedding svg like this, remember to set xmlns

for svg

:

var url = 'data:image/svg+xml;base64,' + 
           btoa('<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"/></svg>');

      



If your svg elements have a prefix xlink

, you should also addxmlns:xlink="http://www.w3.org/1999/xlink"

+15


source







All Articles