html2canvas不能識別svg的解決方案
阿新 • • 發佈:2021-02-05
技術標籤:html+js+jquery+css
最新有個功能需要擷取網頁成圖片,於是用到比較流行的html2canvas,本來以為能順順利利的搞定,後來發現網頁上的流程圖連線線不在截圖中。於是各種百度、bing,也搜到好多,但是感覺沒有一個完整的程式碼,現在自己解決了,分享下程式碼。
首先需要下載canvg.js,github地址:https://github.com/canvg/canvg
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碼,可以轉圖片 //...
$('<img>',{src:
base64Str}).appendTo($('body'))
;//直接在原網頁顯示
} }); } }