Как сохранить svg в base64?

125
01 мая 2021, 12:00

У меня строка содержащая svg тег(не нода). Как мне её сохранить в base64? Данную строку формирует Maker.js. Есть похожий вопрос тут, но там ноду передовать необходимо.

Результат в html:

<svg width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"></line><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"></line><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"></line><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"></line></g></g></g></svg>

Результат Maker.js:

<svg width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"/><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"/><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"/><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"/></g></g></svg>

Ошибка:

Answer 1

Если я правильно Вас понял, Вы ищите это:

let svg = `<svg width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"></line><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"></line><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"></line><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"></line></g></g></g></svg>` 
 
img.src = 'data:image/svg+xml;base64,'+ btoa(svg)
<img id="img">

Еще есть похожий способ, который не требует заворачивания в base64 а работает через encodeURIComponent

let svg = `<svg width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"></line><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"></line><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"></line><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"></line></g></g></g></svg>` 
 
img.src = 'data:image/svg+xml;utf8,'+ encodeURIComponent(svg)
<img id="img">

UPD

Вот фокус чтобы починить теги с самозакрытых на обычные, по крайней мере в хроме и лисе отработал

let svg = `<svg width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"/><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"/><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"/><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"/></g></g></svg>` 
 
let div = document.createElement('div'); 
div.innerHTML = svg; 
 
img.src = 'data:image/svg+xml;base64,'+ btoa(div.innerHTML)
<img id="img">

Answer 2

На вскидку можно так сделать

// исходный SVG 
let s = `<svg width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"></line><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"></line><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"></line><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"></line></g></g></g></svg>`; 
 
// меняем двойные кавычки на одинарные, конвертируем эту строку в base64 и в  
// начало строки дописываем что это закодированная определённым образом строка 
let data_image = 'data:image/svg+xml;base64,' + btoa(s.replace(/\"/g, `'`)); 
img.src = data_image;
<img src="" id="img">

Answer 3

Альтернативный вариант (ссылка в вопросе):

// Cериализация в Xml svg элемента 
let svg = new XMLSerializer().serializeToString(document.getElementById('svg')); 
 
// Строка в base64 
let svg_base64 = 'data:image/svg+xml;base64,' + btoa(svg); 
 
console.log(svg_base64);
<svg id="svg" width="400" height="400" viewBox="-10 -10 220 220" style="padding : 10px" xmlns="http://www.w3.org/2000/svg"><g id="svgGroup" stroke-linecap="round" fill-rule="evenodd" font-size="9pt" stroke="green" stroke-width="0.5mm" fill="none" style="stroke:green;stroke-width:0.5mm;fill:none"><g id="0"><g id="trapeze"><line id="line1" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line1&quot;]" x1="0" y1="200" x2="200" y2="200" vector-effect="non-scaling-stroke"></line><line id="line2" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line2&quot;]" x1="200" y1="200" x2="175" y2="0" vector-effect="non-scaling-stroke"></line><line id="line3" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line3&quot;]" x1="175" y1="0" x2="25" y2="0" vector-effect="non-scaling-stroke"></line><line id="line4" data-route="[&quot;models&quot;,&quot;trapeze&quot;,&quot;paths&quot;,&quot;line4&quot;]" x1="25" y1="0" x2="0" y2="200" vector-effect="non-scaling-stroke"></line></g></g></g></svg>

READ ALSO
Что хуже, бесконечные таймеры или промисы?

Что хуже, бесконечные таймеры или промисы?

Вопрос по работе движка! Что хуже? Бесконечные таймеры или промисы? И почему? Такой вопрос задали на собеседованииКто может пояснить?

149
Слайдер с изображениями вместо точек навигации

Слайдер с изображениями вместо точек навигации

Существует множество готовых плагинов для создания слайдера-карусели на сайтеНе хочется изобретать велосипед, но ни разу не встречала реализация,...

117
Позиционирование блока в меню шапки

Позиционирование блока в меню шапки

пытаюсь переместить второе меню в правую часть экрана, но не выходитЯ плохо разбираюсь в позиционирование элементов, не могли бы вы подсказать...

137
Как анимировать радиальный градиент с помощью CSS?

Как анимировать радиальный градиент с помощью CSS?

Я пытаюсь создать эффект анимации блеска с радиальным градиентом для блока div, но я не уверен, что мой способ, - лучший способ сделать это

138