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

相關文章
相關標籤/搜索