html2canvas截图模糊

1,389 阅读1分钟

工作中使用html2canvas截图模糊,处理方法,更新版本,设置dpi、scale,放大canvas大小。
参考:
blog.csdn.net/qq_27127385…
www.jianshu.com/p/f40063464…

备注:

1:将html内容写入到canvas中

1html2canvas(element,options).then((canvas) =>{})

参数说明:

element:需要将html内容写入canvas的jQuery对象

options:配置信息

常用的配置基本信息:

scale:缩放比例,默认为1

allowTaint:是否允许跨域图像污染画布,默认为false

useCORS:是否尝试使用CORS从服务器加载图像,默认为false

width:canvas画布的宽度,默认为jQuery对象的宽度

height:canvas画布的高度,默认为jQuery对象的高度

backgroundColor:/画布的背景色,默认为透明(#fff),参数可以为#表示的颜色,也可以使用rgba

2:将canvas画布信息转化为base64格式图片

1canvas.toDataURL("image/png")

如果你的html内容中有指定的内容不写入到canvas中的话,你可以给标签添加如下属性

| 1 | data-html2canvas-ignore="true" |

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="baidu-site-verification" content="J0n5tbab1c" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="Copyright" content="Tencent">
    <meta name="format-detection" content="telephone=no">
    <title>合成图片并保存</title>
    <!-- <link rel="stylesheet" href="../css/index.css">
    <script src="../js/adaptive.js"></script> -->
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        html,body{
            height: 100%;
            position: relative;
        }
        #wrap{
            height: 100%;
            background: seashell;
            text-align: center;
            padding-top: 20px;
            position: fixed;
            overflow-y: scroll;
            overflow-x: hidden;
        }
        #capture{
            width: 80%;
            height: 70%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
            border-radius: 15px;
            border: 5px solid #ffffff;
            display: none;
            z-index: 999;
            overflow:scroll;
        }

        #capture img{
            width: 100%;
        }
        h3,p{
            margin-top: 8px;
        }

        #saveImg{
            appearance: none;
            position: absolute;
            bottom: 50px;
            z-index: 888;
            width: 150px;
            height: 30px;
            line-height: 30px;
            border-radius: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: orange;
            color: #ffffff;
        }

        #wrap img{
            width: 80%;
            text-align: center;
        }
        .log{
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 33;
            background: rgba(0, 0, 0, .8);
            display: none;
        }

        #hidden_wrap{
            position: absolute;
            z-index: -10;
            overflow: scroll;

        }
        #hidden_wrap #wrap{
            position: relative;
            overflow: auto;
        }

        #capture .close{
            display: inline-block;
            position: absolute;
            border: 1px solid #ffff;
            color: #ffffff;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            top: -30px;
            right: -5px;
        }
    </style>
</head>

<body>
    <div class="log">
            </div>
    <div id="wrap">
        <h4>家乡的茶园开满花</h4>
        <p>夜夜想起妈妈的话 闪闪的泪光鲁冰花</p>
        <img src="./a.jpg" alt="">
        <h4>家乡的茶园开满花</h4>
        <p>夜夜想起妈妈的话 闪闪的泪光鲁冰花</p>
        <img src="./b.png" alt="">
        <h4>家乡的茶园开满花</h4>
        <p>夜夜想起妈妈的话 闪闪的泪光鲁冰花</p>
        <img src="./c.png" alt="">
        <h4>家乡的茶园开满花</h4>
        <p>夜夜想起妈妈的话 闪闪的泪光鲁冰花</p>
        <img src="./a.jpg" alt="">
        <h4>家乡的茶园开满花</h4>
        <p>夜夜想起妈妈的话 闪闪的泪光鲁冰花</p>
        <img src="./a.jpg" alt="">
        <h4>家乡的茶园开满花</h4>
        <p>夜夜想起妈妈的话 闪闪的泪光鲁冰花</p>
        <img src="./a.jpg" alt="">
         <!-- 合成并保存 -->   
    </div>
    <button  id="saveImg">合成并保存</button>
    <div id="hidden_wrap"></div>

   


    <div id="capture">
        <span class="close">X</span>
        <img src="" alt="" class="copyImage">
    </div>
    <!-- <script src="js/jquery-3.2.1.min.js"></script>
  <script src="./html2canvas.min.js"></script> -->

  <script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <!-- <a id="dl-hidden"  download="合成图.png" href=""></a> -->
    <script>
        // 加载即克隆,克隆完截图赋值,移除克隆元素,点击展示图片
        window.onload = function(){
        var IMAGE_URL;
        $('#wrap').clone().appendTo($('#hidden_wrap'));
        takeScreenshot();
        $('#hidden_wrap #wrap').remove();
        function takeScreenshot(){
            var shareContent = document.getElementById('hidden_wrap');//需要截图的包裹的(原生的)DOM 对象
            // var shareContent = document.getElementsByClassName('page-1')[0];
            var width = shareContent.offsetWidth; //获取dom 宽度
            var height = shareContent.offsetHeight; //获取dom 高度
            console.log('分享元素',$('#hidden_wrap #wrap').height());
            
            console.log('分享元素宽度',width);
            console.log('分享元素高度',height);
            var canvas = document.createElement("canvas"); //创建一个canvas节点

            var scale = 1; //定义任意放大倍数 支持小数
            canvas.width = width * scale; //定义canvas 宽度 * 缩放
            canvas.height = height * scale; //定义canvas高度 *缩放
            canvas.getContext("2d").scale(scale,scale); //获取context,设置scale

            // var rect = shareContent.getBoundingClientRect();//获取元素相对于视察的偏移量
            // canvas.getContext("2d").translate(-rect.left,-rect.top);//设置context位置,值为相对于视窗的偏移量负值,让图片复位
            var opts = {
                scale:scale, // 添加的scale 参数
                canvas:canvas, //自定义 canvas
                logging: true, //日志开关
                width:width, //dom 原始宽度
                height:height, //dom 原始高度
                allowTaint:true,
                logging:true,
                backgroundColor: 'transparent',
            };
            html2canvas(shareContent, opts).then(function (canvas) {
                IMAGE_URL = canvas.toDataURL("image/png");
                $('.copyImage').attr('src',IMAGE_URL);
                // $('#hidden_wrap').css('overflow','hidden');
            })
        }

        function dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        }

        function downloadBase64(dataUrl, filename) {
            var imageFile, href
            // const downloadLink = document.createElement('a')
            var downloadLink = document.getElementById('dl-hidden')
            try {
                var blob = dataURLtoBlob(dataUrl)
                    var href = window.URL.createObjectURL(blob)
                    downloadLink.download = filename
                    downloadLink.href = href
                    downloadLink.click()
            } catch (err) {
            } finally {
                if (href) {
                    window.URL.revokeObjectURL(href)
                }
                // downloadLink.remove()
            }
        }

                // $(".letter-title").text(new Date().toLocaleString());
                $('#saveImg').on('click',function(){
                    // takeScreenshot();
                    $('#capture').show();
                    $('.log').show();
                    $(this).text('长按上图保存图片');
                })
                // var curStyle=0;
                // $("#change-style").click(function(e){
                //         takeScreenshot();
                //         if(curStyle==0){
                //                 $(".letter-content").attr("style","opacity:0.8;");
                //                 $(".letter-bg").attr("style","border-radius:50px;");
                //                 $("#change-style").text("普通");
                //                 curStyle=1;
                //         }else{
                //                 $(".letter-content").attr("style","opacity:1;");
                //                 $(".letter-bg").attr("style","border-radius:0;");
                //                 $("#change-style").text("圆角透明");
                //                 curStyle=0;
                //         }
                // })
                // $("#save-local").click(function(e){
                //         downloadBase64(IMAGE_URL, '合成图.png')
                // })
    }

    </script>
</body>

</html>