Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript - how to convert svg to png image in internet Explorer?

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');
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...