I want to load an SVG image, do some manipulations to its .contentDocument
, and then draw it to a canvas.
A good example for drawing an SVG to a canvas is here: http://www.phrogz.net/tmp/canvas_from_svg.html
But in this example the svg was created as a new Image('url.svg')
object. When you create an SVG that way, it unfortunately doesn't seem to have a contentDocument to manipulate. It only seems to have one when you create it as an <object>
element.
But when I create the SVG as an object, get the SVG's DOM node and pass it to context.drawImage(svgNode, x, y)
, it throws the error "Value could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement."
(on Firefox).
It seems like I either have to find a way to convert an object-SVG to a HTMLImageElement or a way to get the content document of an SVG which was loaded as an Image. Does anyone know how to do either? Or is there a third way to do it which I am missing?
Convert the svg's xml content into string data, then make a data uri out of it. You should be able to load that as an image. Something like this:
Now you should be able to draw it to the canvas.
I managed to do it. The trick was to:
That's my sourcecode:
Edit: Unfortunately it only works in Firefox and Chrome. It fails in IE9 because XMLSerializer() is not supported (it also doesn't support getElementById on XML documents, but there are workarounds for that) and it fails in Opera because createObjectUrl is not supported.