Reputation: 3
I want to convert svg to base64 image. The btoa(xml) is not generating the correct image.
Please find the code here jsFiddle Demo
var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
Can anyone help me with this? Thanks in advance
Upvotes: 0
Views: 2003
Reputation: 13017
To expand a little on LeBeau's answer:
width/height
and viewBox
on the SVG element to fit everything into the image.<svg ... width="700" height="160" viewBox="-40,-120, 700,160">
img
is loaded before you draw in onto the canvas, or else nothing gets drawn.img.onload = e => canvas.getContext('2d').drawImage(img, 0, 0);
https://jsfiddle.net/h2L3gw88/437/
Upvotes: 0
Reputation: 101820
It is encoding fine. It is the style
attribute in your SVG that is causing your problems. Remove it and things get better.
Also, your fiddle was doing unnecessary encoding of the XML before base64 encoding. You don't need that.
var svg64 = btoa(xml);
is fine.
See: https://jsfiddle.net/h2L3gw88/425/
Upvotes: 1