I have an SVG I need to 'convert' to a .png
image, dynamically through JavaScript. The way this is done is the SVG is drawn into a virtual HTML5 canvas element, then converted via the toDataURL
method into a data URI. The code is as follows:
HTML:
<div id="something" data-svg="<svg viewBox='0 0 105 93' xmlns='http://www.w3.org/2000/svg'><path d='M66,0h39v93zM38,0h-38v93zM52,35l25,58h-16l-8-18h-18z' fill='#ED1C24'/></svg>">
JS (using jQuery):
$(function() {
var svgData = $('#something').data('svg');
var imageUrl = svgToImageURL(svgData);
function svgToImageURL(svgString){
var canvas = document.createElement("canvas");
canvas.width = 260;
canvas.height = 260;
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
document.getElementById('something').innerHTML = '<img src="'+png+'"/>';
DOMURL.revokeObjectURL(png);
};
img.src = url;
}
A fiddle can be seen here to demonstrate: https://jsfiddle.net/hejjgu7b/. It should render out the Adobe logo as an image in the page.
It works fine in Chrome and Edge, but in Firefox the image is always empty. It looks like the data URI is malformed in some way, as it's much shorter than that rendered in Chrome/Edge.
I wondered if anyone could see why this is happening, and how to get Firefox to render the correct data URI?
Many thanks.