使用html2canvas实现超出浏览器部分截图

之前写过一篇关于 html2canvas如何在元素隐藏的情况下生成截图 的文章,后面发现还有个坑在等着我,就是如果合成图片太大,超出了浏览器的可视区域,那么超出部分是无法截图的。在网上找到了以下方法,亲测有效~

源码:

return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
        if (typeof(options.onrendered) === "function") {
            log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
            options.onrendered(canvas);
        }
        return canvas;
    });

如下图:

修改为(红色为改动部分):

//解决BUG 对于部分不能截屏不能全屏添加自定义宽高的参数以支持
    var width = options.width != null ? options.width : node.ownerDocument.defaultView.innerWidth;
    var height = options.height != null ? options.height : node.ownerDocument.defaultView.innerHeight;
    return renderDocument(node.ownerDocument, options, width, height, index).then(function (canvas) {
        if (typeof(options.onrendered) === "function") {
            log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
            options.onrendered(canvas);
        }
        return canvas;
    });

如下图:

调用:

$(".js_show_promote").click(function () {
            if(!$(this).hasClass("open")){
                var thisCapture = $(this).find(".js_moneyCode_capture"); //需要捕获的区域
                setTimeout(function(){imgToCanvas(thisCapture);},500);
            }
        });

        function imgToCanvas(captureArea) {
            var captureWidth = $(captureArea).outerWidth(),
                captureHeight = $(captureArea).outerHeight();
            html2canvas($(captureArea), {
                height: captureHeight,
                 captureWidth,
                onrendered: function (canvas) {
                    $(".js_moneyCode_picSmall").attr("src",canvas.toDataURL()).show();
                    $(".js_pic_loading").remove();
                    $(".js_down_moneyCode_pic").attr("href",canvas.toDataURL());
                }
            });
        }

方法已介绍完毕~特别感谢@焰尾迭~提供的解决方案~关于其他更多的坑,可以看看html2canvas 踩坑总结

原文地址:https://www.cnblogs.com/sese/p/8696528.html