通过html2canvas全屏截图

html2canvas 全屏截图 前端截图

最近有个案例需要前端自动截图,以前做过html2canvas自动截图保险投保流程,当时没有记录,这次记录一下,也比较简单。

引入html2canvas.js

https://github.com/niklasvh/html2canvas/releases


只需要下载圈起来的其中一个:

19/eced7392ad3af34b83680082a6f124.png

在需要截图的页面引入js后,给需要截图的div加一个ID:coverScan,然后写一个按钮(class="download"),就可以点击下载截图了:


$(".download").unbind().click(function(){

    html2canvas(document.querySelector("#coverScan")).then(canvas => {

        const imgData = canvas.toDataURL('image/jpeg', 0.7);

        const img = new Image();

        img.src = imgData;

        img.style.width = '100%';

        // 创建弹层显示图片

        const modal = document.createElement('div');

        modal.style.position = 'fixed';

        modal.style.background = 'rgba(0,0,0,0.8)';

        modal.style.top = '0';

        modal.style.left = '0';

        modal.style.right = '0';

        modal.style.bottom = '0';

        modal.style.zIndex = '9999';


        // 添加提示文字

        const tip = document.createElement('div');

        tip.textContent = '长按图片保存到相册';

        tip.style.position = 'fixed';

        tip.style.paddingTop = '5%';

        tip.style.paddingBottom = '5%';

        tip.style.width = '100%';

        tip.style.color = '#fff';

        tip.style.background = 'rgba(0,0,0,0.8)';

        tip.style.top = '0';

        tip.style.fontSize = '24px';

        tip.style.textAlign = 'center';


        modal.appendChild(img);

        modal.appendChild(tip);

        document.body.appendChild(modal);

        removeLoading('scanLoading');

        // 点击关闭弹层

        modal.onclick = () => {

            document.body.removeChild(modal);

        };

    });

});


比较适合移动端,尤其是微信中,不需要后端配合,就可以完美解决图片下载问题。



网站公告

承接各种网站、小程序、H5、公众号、CMS、CRM、OA等系统开发、维护、托管、外包等服务! 邮箱: 3163316168@qq.com