java svgbase64转byte,SVG转换成的base64

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 put into created svg-element and convert it into base64, but if I try to open a link I find that svg does not render on the page.

var xmlns = 'http://www.w3.org/2000/svg',

IMAGE_TEMPLATE = document.createElementNS(xmlns, 'svg');

IMAGE_TEMPLATE.appendChild(document.body.querySelector('#ico-appliance-thermostat-128'));

IMAGE_TEMPLATE.setAttribute('id', 'svg');

IMAGE_TEMPLATE.setAttributeNS(null, 'width', 128);

IMAGE_TEMPLATE.setAttributeNS(null, 'height', 128);

IMAGE_TEMPLATE.setAttributeNS(null, 'viewBox', '0 0 128 128');

document.body.querySelector('#test').appendChild(IMAGE_TEMPLATE);

test = function(){

var s = new XMLSerializer().serializeToString(document.getElementById("svg"))

var encodedData = window.btoa(s);

console.log('data:image/svg+xml;base64,' + encodedData);

}

解决方案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:

//Force refresh svg

var svg = document.body.querySelector('#test').innerHTML;

document.body.querySelector('#test').innerHTML = "";

document.body.querySelector('#test').innerHTML = svg;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值