Convert svg into base64

前端 未结 4 1350
误落风尘
误落风尘 2020-12-20 05:53

SVG which was created programmatically does not convert into base64 correctly.

In my application I\'ve got a service which get a response with g-element and then pu

4条回答
  •  渐次进展
    2020-12-20 06:06

    Difference between @guest271314 and my answer:

    @guest271314 his answer:

    Wrap the g element inside a svg element to make sure that the browser renders the g element onload.

    My answer:

    Forces the svg element inside #test to render the g element since the g element wasn't rendered onload.

    Best answer in this case: @guest271314

    Reason: A g element should be inside a svg element in valid html.

    When should my answer be used?
    In the case that the g element is not an element in the html document.

    You didn't close test() with a }. Code below returns a base64 encoded svg: https://jsfiddle.net/seahorsepip/6sra5c5L/1/

    Edit:

    svg render issue is something I ran into myself before, here's the fix with a line of jquery: https://jsfiddle.net/seahorsepip/6sra5c5L/3/

    //Force refresh svg
    $("#test").html($("#test").html());
    

    Here's the original SO thread about the issue: jquery's append not working with svg element?

    I don't know the javascript equivalent for the jQuery code I added, I tried to write it but it didn't work :/

    Edit 2:

    Here's the pure js equivalent:

    https://jsfiddle.net/seahorsepip/6sra5c5L/4/

    //Force refresh svg
    var svg = document.body.querySelector('#test').innerHTML;
    document.body.querySelector('#test').innerHTML = "";
    document.body.querySelector('#test').innerHTML = svg;
    

提交回复
热议问题