问题
Goal - using the client-side:
Convert a dynamic SVG drawing (created using d3js) to a downloadable PNG image and works using Internet Explorer.
Accomplished:
Achieved in Chrome, no problem. Once I have the PNG DataURI it is easily converted to a downloadable PNG blob.
Unfortunately in IE running the same code produces a SecurityException, it fails when I try to convert the canvas to the PNG DataURI (canvas.toDataURL).
Apparently this is an active IE BUG and I've found others on StackExchange with the same issue. I believe it is related to the CORS restrictions applied on images that originate from other domains (and are drawn in a canvas), but my SVG has originated from the local page.
Thoughts
Wondering if the cause is related to the way I was generating the initial DataURI (data:image/svg+xml) for the SVG drawing that is rendered by the IMG element.
I have tried two alternatives to produce the image/svg+xml, base64 and charset=utf8, but they have not overcome the issue encountered. So wondering if it is the content of the SVG, presently there are no images within the SVG drawing.
Code for reference:
var rawSvg = new XMLSerializer().serializeToString(svgElement);
var img3 = new Image();
document.body.appendChild(img3);
var canv = document.createElement("canvas");
var canv_ctx = canv.getContext("2d");
img3.onload = function () {
//-- Image has loaded using the native data:image/svg+xml
canv_ctx.drawImage(this, 0, 0);
//-- IE Will throw a Security Exception here...
console.log(canv.toDataURL("image/png"));
};
img3.src = "data:image/svg+xml;base64," + btoa(rawSvg);
//-- Or utf8
//img3.src = "data:image/svg+xml;charset=utf8," + encodeURIComponent(rawSvg);
UPDATE:
Tested Canvg's extension to 2d context "drawSvg(...)" which draws onto the canvas. This overcomes the SecurityException when calling toDataURL on the canvas element, however the draw function is not accurate enough for text rendering and placement. So I am still in need of a solution.
See example screenshot, left correct rending using native drawImage and right the incorrect rendering using Canvg's drawSvg
Code using Canvg - NB: You'll need to reference the JS
var canvas = document.createElement("canvas"),
cctx = canvas.getContext("2d");
var rawSvg = new XMLSerializer().serializeToString(svgClone.node());
canvas.width = svgWidth;
canvas.height = svgHeight;
//cctx.drawImage(this, 0, 0);
//-- Use Canvg's extension to canvasContext
cctx.drawSvg(rawSvg);
//-- This Works on IE - not accurate though
var dataURL = canvas.toDataURL();
来源:https://stackoverflow.com/questions/36321936/convert-dynamic-svg-to-downloadable-png-in-ie