html2canvas不能识别svg的解决方案

  最新有个功能须要截取网页成图片,因而用到比较流行的html2canvas,原本觉得能顺顺利利的搞定,后来发现网页上的流程图链接线不在截图中。因而各类百度、bing,也搜到好多,可是感受没有一个完整的代码,如今本身解决了,分享下代码。html

  

  首先须要下载canvg.js,github地址:https://github.com/canvg/canvgnode

function showQRCode() {
                scrollTo(0, 0);
               
                if (typeof html2canvas !== 'undefined') {
                    //如下是对svg的处理
                    var nodesToRecover = [];
                    var nodesToRemove = [];
                    var svgElem = $("#divReport").find('svg');//divReport为须要截取成图片的dom的id
                    svgElem.each(function (index, node) {
                        var parentNode = node.parentNode;
                        var svg = node.outerHTML.trim();

                        var canvas = document.createElement('canvas');
                        canvg(canvas, svg); 
                        if (node.style.position) {
                            canvas.style.position += node.style.position;
                            canvas.style.left += node.style.left;
                            canvas.style.top += node.style.top;
                        }

                        nodesToRecover.push({
                            parent: parentNode,
                            child: node
                        });
                        parentNode.removeChild(node);

                        nodesToRemove.push({
                            parent: parentNode,
                            child: canvas
                        });

                        parentNode.appendChild(canvas);
                    });
                    html2canvas(document.querySelector("#divReport"), {
                        onrendered: function(canvas) {
                            var base64Str =canvas.toDataURL();//base64码,能够转图片

                            //...
base64Str;//直接在原网页显示$('<img>',{src:}).appendTo($('body'))
                         } 
});
}
}

 

by QJLgit

相关文章
相关标签/搜索