2

У меня строка содержащая 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>

Ошибка:

введите сюда описание изображения

5
  • Маркера xml у тебя не хватает, а в остальном всё как всегда.
    – Qwertiy
    29 июл 2019 в 11:28
  • @Qwertiy,а по конкретнее)
    – doox911
    29 июл 2019 в 11:32
  • лучше конечно было бы увидеть сразу результирующую svg 29 июл 2019 в 13:54
  • @StrangerintheQ подправил.
    – doox911
    29 июл 2019 в 14:06
  • @doox911 смотрите ответ 29 июл 2019 в 14:12

3 ответа 3

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">

4
  • Спасибо. Первый вариант пробовал, почему-то не отрабатывал)
    – doox911
    29 июл 2019 в 11:40
  • Maker.js методом makerjs.exporter.toSVG() возвращает самозакрывающиеся теги, а броузеры перепарсивают на обычные теги. Например: <line/> в <line></line>.
    – doox911
    29 июл 2019 в 13:37
  • Да) Метод ваш рабочий, но броузер ругается и не открывает.
    – doox911
    29 июл 2019 в 13:44
  • Конечно, костльненько)
    – doox911
    29 июл 2019 в 14:15
1

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

// исходный 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">

1

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

// 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>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.