NS1 namespace prefix for href on% tagElement% undefined, setAttributeNS

I got this error in safari while trying to convert svg to base64 url โ€‹โ€‹through code:

$svgCopy = $('svg').clone()
html = $('<div>').append($svgCopy).html()
imgSrc = 'data:image/svg+xml;base64,' + btoa(html)
imgEl.src = imgSrc

The problem is that when you set the attribute using NS (setAttributeNS), safari sets the NS \ d + namespace and does not set the xmlns: NS \ d + attribute in svg, so it looks like

<use NS1:href="#source" />

When you copy such an svg to Chrome, you have no such problem, because this svg element will look like this:

<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#source" />

And as a result (on svg copy) we get an invalid file.

UPD: @Robert with setAttributeNSeverything ok:

el.setAttributeNS('http://www.w3.org/1999/xlink', 'href', '#source')

Without a proper call, it will not work in Chrome.

+4
source share
1 answer

, :

html = html.replace(/NS\d+:href/gi, 'xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href')

.

: Firefox xmlns:xlink="http://www.w3.org/1999/xlink , Safari , Root:

draw.canvas.setAttributeNS('http://www.w3.org/2000/svg', 'xlink', 'http://www.w3.org/1999/xlink') 

html svg base64:

// Firefox, Safari root NS issue fix
html = html.replace('xlink=', 'xmlns:xlink=')
// Safari xlink NS issue fix
html = html.replace(/NS\d+:href/gi, 'xlink:href')
+4

All Articles