Canvg not working with svg already placed in body?

I want to convert my SVG to CANVAS and then save it as an image. I have svg already genreated javascript on my page. I am using this code:

$("#menu-save-image").click(function () {
    var svg = document.getElementsByTagName('svg');
    var canvas = document.getElementById("test");
    canvg(canvas, svg);

    // or second way
    var c = document.getElementById('test');
    var ctx = c.getContext('2d');
    ctx.drawSvg(svg, 0, 0, 500, 500);


});

      

Both methods don't work. Why?

+3


source to share


1 answer


The canvg method needs an SVG source string (or url or XMLDocument), so you need to convert the svg element to svg source using the XMLSerializer as follows.

var svg = document.querySelector('svg');
var serializer = new XMLSerializer();
var svgString = serializer.serializeToString(svg);
var canvas = document.getElementById("test");
canvg(canvas, svgString);

      



see https://code.google.com/p/canvg/source/browse/trunk/canvg.js

+7


source







All Articles