canvg doesn't work with svg already placed in body?

我们两清 提交于 2019-12-06 08:22:34

问题


I want to converty my SVG into CANVAS and then save it as image. I have svg already genereated by javascript in my page. I use 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 ways doesn't work. Why?


回答1:


canvg method needs SVG source string (or url or XMLDocument), so you should convert the svg element to svg source by using XMLSerializer like this.

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



来源:https://stackoverflow.com/questions/25461405/canvg-doesnt-work-with-svg-already-placed-in-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!