Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I managed to do it. The trick was to:</p> <ol> <li>use XMLHttpRequest() to load the SVG as an XML document</li> <li>manipulate that XML document</li> <li>convert the XML document to a string</li> <li>create an ObjectURL from that string</li> <li>create an Image with that ObjectURL</li> <li>copy that Image to the canvas</li> </ol> <p>That's my sourcecode:</p> <p><strong>Edit:</strong> 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.</p> <pre><code>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(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload