当前位置 博文首页 > html2 canvas svg不能识别的解决方案

    html2 canvas svg不能识别的解决方案

    作者:风一样的大叔 时间:2021-06-04 18:02

      最新有个功能需要截取网页成图片,于是用到比较流行的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'));//直接在原网页显示
                             }                     });                }            }
    js