I'm creating a dynamically-generated SVG from HTML text content. It works fine in Chrome but Safari consistently throws an error when the SVG data is converted to PNG for downloading.
What has me puzzled is that there is no cross-browser stuff happening; this is all being generated/downloaded from a single source. Even so, including img.crossOrigin = ‘Anonymous’
has not helped Safari to overcome its problem with (presumably) the canvas's origin-clean
state.
function makeImage(canvas, pHeight, content) {
var ctx = canvas.getContext('2d');
var svgElementCode = '<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" version="1.1" width="800" height="600">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="height:' + (pHeight - 100) + 'px; font-size: 20px;">' +
content +
'</div>' +
'</foreignObject>' +
'</svg>';
var data = 'data:image/svg+xml,' + encodeURIComponent(svgElementCode);
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = data;
img.onload = function() {
ctx.drawImage(img, 0, 0);
var canvasdata = canvas.toDataURL("image/png");
var pngimg = '<img src="'+canvasdata+'">';
$("#shareImage").append($('<a href="' + canvasdata + '" title="file.svg">' + pngimg + '</a>'));
};
}
I don't know what canvas/SVG horrors may lie in other browsers, but for now I'd just like to see this working in Safari. Any ideas?
UPDATE
It seems that with the foreignObject
tag the SVG cannot be written to canvas, yet this tag might be partly responsible for Safari's security exception (a dirty canvas). As soon as canvas.toDataURL
is encountered by Safari, it throws the security error. In fact, it seems that even the svg-todataurl.js plugin--apparently written TO DO JUST THIS--cannot overcome this same basic problem in Safari.
Interestingly, this problem also happens in all versions of IE up until Edge (non IE anyway?); in Edge the canvas.toDataURL
function works. Hmm.
UPDATE 2
@Kaiido's suggestion: Use html2canvas. If you're not doing any cross-origin stuff then this is all you might need for rendering DOM elements as pixels. Thanks Kaiido.
UPDATE 3
html2canvas: NEGATORY. Try downloading the test image generated on their examples page, using Safari. Same problem, so not a solution.