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

javascript - Base64 SVG images - Stack Overflow

programmeradmin5浏览0评论

I cannot get a base64 data URI for and SVG to appear as an image.

I tried an <img> and a <canvas> and for neither one does the SVG show up.

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>

I cannot get a base64 data URI for and SVG to appear as an image.

I tried an <img> and a <canvas> and for neither one does the SVG show up.

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>

Tested in Chrome and Firefox.

What doesn't the SVG show up?

Share Improve this question edited Sep 27, 2014 at 19:40 Paul Draper asked Sep 27, 2014 at 19:34 Paul DraperPaul Draper 83.3k52 gold badges213 silver badges301 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 17

When embeding svg like this, remember to set xmlns for the svg:

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

If there is any xlink prefix used in your svg elements, you should also add xmlns:xlink="http://www.w3/1999/xlink"

发布评论

评论列表(0)

  1. 暂无评论