Drawing a modified SVG on canvas

I want to load an SVG image, do some manipulation of its .contentDocument , and then draw it on the canvas.

A good example for drawing SVG on canvas can be found here: http://www.phrogz.net/tmp/canvas_from_svg.html

But in this example, svg was created as a new Image('url.svg') object new Image('url.svg') . When you create an SVG in this way, unfortunately, it has no manipulation of the contentDocument. It seems to be only one when you create it as a <object> element.

But when I create the SVG as an object, get the SVG 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." (in Firefox).

It seems I either have to find a way to convert the SVG object to an HTMLImageElement element, or a way to get the SVG content document that was loaded as an image. Does anyone know how to do this? Or is there a third way to do this that I am missing?

+3
source share
2 answers

I have succeeded. The trick was this:

  • use XMLHttpRequest () to load the SVG as an XML document.
  • manipulate this xml document
  • convert xml document to string
  • create ObjectURL from this line
  • create an image with this object url
  • copy this image to the canvas

What is my source code:

Edit: Unfortunately, it only works in Firefox and Chrome. It does not work in IE9 because XMLSerializer () is not supported (it also does not support getElementById in XML documents, but there are workarounds for this), and it does not work in Opera because createObjectUrl is not supported.

 var xhr = new XMLHttpRequest(); xhr.onload = function() { // get the XML tree of the SVG var svgAsXml = xhr.responseXML; // do some modifications to the XML tree var element = svgAsXml.getElementById('hat'); element.style.fill = '#ffff00'; // convert the XML tree to a string var svgAsString = new XMLSerializer().serializeToString(svgAsXml); // create a new image with the svg string as an ObjectUrl var svgBlob = new Blob([svgAsString], {type: "image/svg+xml;charset=utf-8"}); var url = window.URL.createObjectURL(svgBlob); var img = new Image(); img.src = url; // copy it to the canvas img.onload = function() { var theCanvas = document.getElementById('theCanvas'); var context = theCanvas.getContext('2d'); context.drawImage(img, 0, 0); window.URL.revokeObjectURL(svgBlob); } } xhr.open("GET", "test.svg"); xhr.responseType = "document"; xhr.send(); 
+1
source

Convert svg xml contents to string data, then make uri data from it. You can download this image. Something like that:

 new Image("data:image/svg+xml," + svgdata); 

Now you can draw it on canvas.

+1
source

All Articles