Home > Net >  Strange bug converting images into Base64 string for SVG element
Strange bug converting images into Base64 string for SVG element

Time:09-07

I found a way to convert images from the users file system to a Base64 string to add it to an SVG element :

const importLogo = document.querySelector('input#import-logo')

function encodeImageFileAsURL(){ // Fired onchange from the input element html

    var file = importLogo.files[0]
    var reader = new FileReader()

    reader.readAsDataURL(file)

    reader.onloadend = function() {
            
        let logoImg = document.createElement('image')
        logoImg.setAttribute('xlink:href', reader.result)
        logoImg.setAttribute('height', '1000')
        logoImg.setAttribute('width', '3000')
        logoImg.setAttribute('x', '0')
        logoImg.setAttribute('y', '0')
            

        clickedLogoElement.parentNode.appendChild(logoImg)
        clickedLogoElement.remove()

        }
    }

The image is well appended where it needs to be :

enter image description here

The problem is that this image doesn't appears on screen and the very strange part is that I can make it appears from the devtool, copying the <image> element, "Edit as HTML" from the parent <g id="logo_group">"and paste it anywhere inside. After that, the original AND the pasted one appear on the screen and if I delete one or the other the last one remains appearing..

Why ? And how can I do to make it appears at first ?

CodePudding user response:

You need to use the svg and xlink namespaces with SVG. All elements are in the svg namespace and the xlink:href attribute is in the xlink namespace.

So you need these changes to your code:

let logoImg = document.createElementNS('http://www.w3.org/2000/svg', 'image')
logoImg.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', reader.result)

Although these days most browsers do support href in the null namespace too.

  • Related