I know that the image must be complete, its loading finished before using the toDataURL function on the canvas, put the code in the image.onload function ensures that.
A
You need to set absolute width
and height
attributes to your root svg node (e.g in px
).
The default is 100%
but FF has no way to know relative to what (specs don't say yet). `
Chrome makes it relative to something that only they know.
So FF won't draw your svg image, on the canvas, but won't fire an error either, since the image has loaded correctly (in an html document, they could know what the dimensions should be relative to).
var xmlSource = '';
function callback(dataURI){
var img = new Image();
img.src = dataURI;
document.body.appendChild(img);
console.log(dataURI);
}
var imageWidth = imageHeight = 45;
var image = new Image();
image.onload = (function (imageWidth, imageHeight) {
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var context = canvas.getContext('2d', {preserveDrawingBuffer : true});
context.drawImage(image, 0, 0, imageWidth, imageHeight);
var dataURL;
dataURL = canvas.toDataURL("image/png");
callback(dataURL);
}).bind(this, imageWidth, imageHeight);
image.onerror =
image.onabort = function () {
console.error("generateIcon : error on image");
}
image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(xmlSource).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}));