how to convert svg to png image in internet Explorer?

隐身守侯 提交于 2019-12-23 04:37:27

问题


i have a chart that created with highchart. i need to save svg to png in internet Explorer. i use from follow code and exist security Error in ie11.

var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
var imgChart = document.createElement('img');
imgChart.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg))));
imgChart.onload = function () {
    ctx.drawImage(imgChart, 0, 0);
    var blobObject = canvas.msToBlob();
    window.navigator.msSaveBlob(blobObject, 'save.png');
})

回答1:


I didn't found an satisfying dupe target, so I'll rewrite it as an answer :


Drawing an SVG image through drawImage method will taint the canvas in IE < Edge for security reasons.

This operation is somehow sensitive for browsers, since svg images imply to parse some XML, and that it can contain some tricky elements (though IE doesn't support <foreignObject>...)
So quite often, browsers will add security restrictions when SVG images are drawn to it, and will block all exporting methods.

This is the case in safari > 9 when an <foreignObject> is drawn on it, this was also the case in chrome, but only when the image comes from an Blob (an implementation bug, but they finally leveraged the security restriction altogether anyway).
And then in IE < Edge, with any SVG.

The only way to workaround this issue is to parse yourself the SVG, and then use the canvas' methods to reproduce it.

This is all doable, but can take some time to implement, so even though I don't really like it, you'd probably be better using an library like canvg, which does exactly this (parsing + rendering with canvas methods).



来源:https://stackoverflow.com/questions/44225871/how-to-convert-svg-to-png-image-in-internet-explorer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!