I want to download an SVG image in my DOM. I've searched around on stack overflow and the common approach to do this is following these steps:
Serialize the svg to a XML string
var svgImage = document.getElementById('maskedImage')
var svgXML = (new XMLSerializer).serializeToString(svgImage)
Create a javascript Image with the XML string as a source
var img = new Image();
var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
/* next steps go here */
}
img.src = url;
Draw that Image on a canvas
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
canvas.width = width
canvas.height = height
ctx.drawImage(img, 0,0, width, height)
Dump the canvas to an URL and make the user download that
window.open(canvas.toDataURL('image/png')) // not the point of the question
The thing is, my SVG has an <image>
tag with an SVG mask (which is a black and white <image>
). To make things worse, one of these images has an object URL (those returned by URL.createObjectUrl(...)
). These are requirements and cannot be changed.
Following the mentioned process, the initial SVG "looses" images on the second step. The image img
doesn't display the <image>
, even if I remove the mask and display.
I've also tried removing the mask and changing the <image>
url from something created with URL.createObjectURL
to an inline image (data:image/png;base64,...
), to a dummy URL (http://www.tuvotacion.com/imagenes_unicas/cual-perrito-es-mas-tierno-450089.jpg
) and I'm still not able to display images.
Note that this question is not a duplicate of all the questions asking how to download an SVG, but a special case when you have images.
The question
How can I "translate" my SVG to an image without loosing <image>
s, so I can effectively print it on the canvas?