Skip to content Skip to sidebar Skip to footer

Drawing A Modified Svg To A Canvas

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.n

Solution 1:

I managed to do it. The trick was to:

  1. use XMLHttpRequest() to load the SVG as an XML document
  2. manipulate that XML document
  3. convert the XML document to a string
  4. create an ObjectURL from that string
  5. create an Image with that ObjectURL
  6. copy that Image to the canvas

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.

var xhr = newXMLHttpRequest();
xhr.onload = function() {
    // get the XML tree of the SVGvar svgAsXml = xhr.responseXML;
    // do some modifications to the XML treevar element = svgAsXml.getElementById('hat');
    element.style.fill = '#ffff00';
    // convert the XML tree to a stringvar svgAsString = newXMLSerializer().serializeToString(svgAsXml);
    // create a new image with the svg string as an ObjectUrlvar svgBlob = newBlob([svgAsString], {type: "image/svg+xml;charset=utf-8"});
    var url = window.URL.createObjectURL(svgBlob);
    var img = newImage();
    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();

Solution 2:

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:

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

Now you should be able to draw it to the canvas.

Post a Comment for "Drawing A Modified Svg To A Canvas"