Quiero enviar una imagen SVG en línea a un script PHP para convertirla a PNG con Imagick. Para eso, tengo que saber cómo obtener un String base64 en un SVG en línea. Para objetos de lienzo es un simple ".toDataURL()" pero eso no funciona con SVG en línea, porque no es una función global de elementos.
test = function(){ var b64 = document.getElementById("svg").toDataURL(); alert(b64); }http://jsfiddle.net/nikolang/ccx195qj/1/
Pero, ¿cómo hacerlo para SVG en línea?
Use XMLSerializer para convertir el DOM en una cadena
var s = new XMLSerializer().serializeToString(document.getElementById("svg"))y luego btoa puede convertir eso a base64
var encodedData = window.btoa(s); Simplemente anteponga la introducción de URL de datos, es decir data:image/svg+xml;base64, y ahí lo tiene.
Solo trato de recopilar y explicar todas las grandes ideas sobre este tema. Esto funciona tanto en Chrome 76 como en Firefox 68
var svgElement = document.getElementById('svgId'); // Create your own image var img = document.createElement('img'); // Serialize the svg to string var svgString = new XMLSerializer().serializeToString(svgElement); // Remove any characters outside the Latin1 range var decoded = unescape(encodeURIComponent(svgString)); // Now we can use btoa to convert the svg to base64 var base64 = btoa(decoded); var imgSource = `data:image/svg+xml;base64,${base64}`; img.setAttribute('src', imgSource);Puede hacerlo de manera relativamente sencilla de la siguiente manera. La versión corta es
svg de origenbase64 codifique el svg fuente, agregue los datos relevantes, configure img src Obtenga el contexto del canvas ; .drawImage la imagen
<script type="text/javascript"> window.onload = function() { paintSvgToCanvas(document.getElementById('source'), document.getElementById('tgt')); } function paintSvgToCanvas(uSvg, uCanvas) { var pbx = document.createElement('img'); pbx.style.width = uSvg.style.width; pbx.style.height = uSvg.style.height; pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML); uCanvas.getContext('2d').drawImage(pbx, 0, 0); } </script> <svg xmlns="http://www.w3.org/2000/svg" width="467" height="462" id="source"> <rect x="80" y="60" width="250" height="250" rx="20" style="fill:#ff0000; stroke:#000000;stroke-width:2px;" /> <rect x="140" y="120" width="250" height="250" rx="40" style="fill:#0000ff; stroke:#000000; stroke-width:2px; fill-opacity:0.7;" /> </svg> <canvas height="462px" width="467px" id="tgt"></canvas>JSFiddle: https://jsfiddle.net/oz3tjnk7/