首页 > 技术文章 > html2canvas以及domtoimage的使用踩坑总结 动态获取的二维码失效如何生成海报

lipengze 2019-09-18 16:28 原文

//判断手机为安卓还是ios  安卓html2canvas方法  ios系统dom-to-image方法        
$(".code").click(function() {
    var u = navigator.userAgent;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    if(isiOS) {
        window.location.href = "mycodeios.html"
    } else if(isAndroid) {
        window.location.href = "mycode.html"
    }
})

安卓html2canvas方法

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
        <title>分享</title>
        <link rel="stylesheet" type="text/css" href="css/reset.css" />
        <style type="text/css">
            /*头部*/
            
            body {
                background: #FFFFFF;
                height: 0 !important;
            }
            
            .container {
                max-width: 750px;
                min-width: 32px;
                margin: 0 auto;
                background: #FFFFFF;
            }
            
            .zhe {
                position: fixed;
                max-width: 750px;
                min-width: 32px;
                width: 100%;
                height: 100%;
                background: #45A196;
                z-index: 9;
            }
            
            .imge {
                position: absolute;
                max-width: 750px;
                min-width: 32px;
                width: 90%;
                height: 100%;
                margin: 0% 5%;
                z-index: 99;
                /*background: url(codeimg/code.jpg) no-repeat;*/
                /*background-size: contain;*/
            }
            
            .left {
                position: absolute;
                left: 12%;
                top: 70%;
                color: #FFFFFF;
                font-size: 26px;
                letter-spacing: 5px;
            }
            
            .bottom {
                position: absolute;
                right: 38%;
                top: 65%;
            }
            
            .codebotom {
                position: absolute;
                padding: 10px;
                background: #FFFFFF;
                width: 90px;
                height: 90px;
            }
            
            .butright_img {
                position: absolute;
                width: 80px;
                height: 80px;
                margin: 5px;
                top: 0px;
                left: 0px;
            }
            
            .textbottom {
                position: absolute;
                width: 40px;
                letter-spacing: 5px;
                color: #FFFFFF;
                top: 20px;
                left: -45px;
            }
            
            .butright {
                position: absolute;
                bottom: 50px;
                right: 15%;
                color: #4BA59B;
                padding: 10px 20%;
                border-radius: 3px;
                z-index: 9999;
                color: #ffffff;
                text-align: center;
            }
            
            .image {
                display: block;
                max-width: 750px;
                min-width: 32px;
                width: 100%;
                position: absolute;
                top: 0px;
                left: 0px;
                background: #FFFFFF;
                z-index: 9999;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <!--二维码-->
            <div class="zhe"></div>
            <div class="imge">
                <div style="position: absolute; top: 0px; left: 0px;">
                    <img src="codeimg/code.jpg" />
                </div>
                <div style="width: 100%;height: 100%; position: relative;">
                    <div class="left state"></div>
                    <div class="bottom">
                        <div class="textbottom">扫码立即注册</div>
                        <div class="codebotom">
                            <!--<div id="qrcode" class="butright_img"></div>-->                        
                        </div>
                    </div>
                </div>
                <div>
                    <div class="butright">长按保存图片</div>
                </div>
            </div>
            <div class="image" style="display: block;">

            </div>

        </div>
    </body>
    <script src="js/config.js"></script>
    <script src="js/jquery-2.1.4.min.js" type="text/javascript" charset="utf-8"></script>
    <!--<script src="js/fenxiang.js" type="text/javascript" charset="utf-8"></script>-->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <!--二维码-->
    <script src="js/jquery.qrcode.logo.min.js" type="text/javascript" charset="utf-8"></script>
    <!--html2canvas图片-->
    <script type="application/javascript" src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script type="text/javascript">
        //  倒计时  
        $(function() {
            var openid_list = eval(decodeURIComponent(localStorage.getItem("openid")))
            var openid = openid_list[1]
            var access_token = openid_list[0]
            
            /*监听返回 iosbug*/
            window.history.pushState(null, null, "#");
            window.addEventListener('popstate', function(e) {
                window.location.href = 'my.html'
            }, false);

            //创建二维码
            /*function createQRCode(id, url, width, height, src) {
                $('#' + id).empty();
                jQuery('#' + id).qrcode({
                    render: 'canvas',
                    text: url,
                    width: width, //二维码的宽度  
                    height: height, //二维码的高度  
                    imgWidth: width / 6, //图片宽
                    imgHeight: height / 6, //图片高
                    src: src //图片中央的二维码
                });
            }
            var url = 'https://api.gzkny.com/h5/aa.html?openid=' + openid;
            createQRCode("qrcode", url, 80, 80, "image/follow.jpg");*/
            
            
             /*使用html2canvas 转换html为canvas 安卓html2canvas方法*/
            function downloadForJS(src) {  
                html2canvas(document.body, {
                    useCORS: true,
                    logging: true,
                    allowTaint: false, //允许跨域(图片跨域相关)
                }).then(function(canvas) {
                    var imgUri = canvas.toDataURL().replace("image/png", "image/octet-stream"); // 获取生成的图片的url  
//                    console.log(imgUri)
                    console.log('完成')
                    $('.image').html('<img  src="' + imgUri + '"/>')
                });
            }

            /**
             * 将图片转换为base64
             * 解决html2canvas跨域合成失败的问题
             */
            /*第一种方法*/
            function getBase64Image(img) {
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var dataURL = canvas.toDataURL("image/png"); // 可选其他值 image/jpeg
                return dataURL;
            }
            function main(src, cb) {
                var image = new Image();
                image.src = src + '?v=' + Math.random(); // 处理缓存
                image.crossOrigin = "anonymous"; // 支持跨域图片
                image.setAttribute('crossorigin', ' *' ) // 支持跨域图片
                image.onload = function() {
                    var base64 = getBase64Image(image);
                    cb && cb(base64);
                }
            }

            /*第二种方法*/
            function getBase64ByUrl(src, callback, outputFormat) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', src, true);
                xhr.responseType = 'arraybuffer';
                xhr.onload = function(e) {
                    if(xhr.status == 200) {
                        var uInt8Array = new Uint8Array(xhr.response);
                        var i = uInt8Array.length;
                        var binaryString = new Array(i);
                        while(i--) {
                            binaryString[i] = String.fromCharCode(uInt8Array[i]);
                        }
                        var data = binaryString.join('');
                        var base64 = window.btoa(data);
                        var dataUrl = "data:" + (outputFormat || "image/png") + ";base64," + base64;
                        console.log(dataUrl)
                        callback.call(this, dataUrl);
                    }
                };
                xhr.send();
            }
            
            /*第三种方法*/
            function getBase64(imgUrl) {
                window.URL = window.URL || window.webkitURL;
                var xhr = new XMLHttpRequest();
                xhr.open("get", imgUrl, true);
                // 至关重要
                xhr.responseType = "blob";
                xhr.onload = function() {
                    if(this.status == 200) {
                        //得到一个blob对象
                        var blob = this.response;
                        console.log("blob", blob)
                        // 至关重要
                        let oFileReader = new FileReader();
                        oFileReader.onloadend = function(e) {
                            let base64 = e.target.result;
                            console.log("方式一》》》》》》》》》", base64)
                        };
                        oFileReader.readAsDataURL(blob);
                        //====为了在页面显示图片,可以删除====
                        var img = document.createElement("img");
                        img.onload = function(e) {
                            window.URL.revokeObjectURL(img.src); // 清除释放
                        };
                        let src = window.URL.createObjectURL(blob);
                        img.src = src
                        document.getElementById("container1").appendChild(img);
                        //====为了在页面显示图片,可以删除====
                    }
                }
                xhr.send();
            }

            // 获取二维码URL
            $.ajax({
                method: 'GET',
                url: window.BASE_URL + 'wx/accessToken',
                contentType: 'application/x-www-form-urlencoded',
                async: false,
                dataType: "json",
                data: {
                    openid: openid
                },
                success: function(data) {
                    console.log(data)
                    //    $('.butright_img').attr('src', 'http://res.gzkny.com/9fdd7a57-3b4e-4c71-9aa9-ba28e766ed4c.jpg')
                    //    $('#qrcode').html('<img src="' + data.data.url + '"/>')
                    // getBase64ByUrl('http://res.gzkny.com/9fdd7a57-3b4e-4c71-9aa9-ba28e766ed4c.jpg')
                    // getBase64('http://res.gzkny.com/9fdd7a57-3b4e-4c71-9aa9-ba28e766ed4c.jpg')
                    /*图片可能会跨域  把图片url转为base64*/
                    main(data.data.url, function(base64) {
                        console.log(base64)
                        $('.codebotom').html('<img class="butright_img"  src="' + base64 + '"/>')                    
                  });
                    // 获取数据
                    $.ajax({
                        method: 'GET',
                        url: window.BASE_URL + 'api/v1/member/get',
                        contentType: 'application/x-www-form-urlencoded',
                        async: false,
                        dataType: "json",
                        data: {
                            access_token: access_token,
                        },
                        success: function(data) {
                            console.log(data)
                            if(data.error == 'success') {
                                $('.state').html(data.data.username)
                                /*执行代码转海报*/
                                setTimeout(function() {
                                    downloadForJS()
                                }, 1000)
                            }
                        }
                    });
                }
            });
        })
    </script>

</html>

ios系统dom-to-image方法

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>分享</title>
        <script src="js/jquery-2.1.4.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" src="js/dom-to-image.js"></script>
        <script type="text/javascript" src="js/FileSaver.js"></script>
        <style type="text/css">
            /*头部*/
            
            * {
                margin: 0px;
                padding: 0px;
            }
            
            body {
                background: #45A196;
                width: 100%;
                height: 100%;
            }
            
            .container {
                max-width: 750px;
                min-width: 32px;
                margin: 0 auto;
                position: relative;
            }
            
            .imge {
                position: relative;
                max-width: 750px;
                min-width: 32px;
                width: 100%;
                height: 100%;
                z-index: 99;
            }
            
            .left {
                position: absolute;
                left: 12%;
                margin-top: 116%;
                color: #FFFFFF;
                font-size: 26px;
                letter-spacing: 5px;
            }
            
            .bottom {
                position: absolute;
            }
            
            .codebotom {
                position: absolute;
                background: #FFFFFF;
                width: 90px;
                height: 90px;
            }
            
            .butright_img {
                position: absolute;
                width: 80px;
                height: 80px;
                margin: 5px;
                top: 0px;
                left: 0px;
            }
            
            .textbottom {
                position: absolute;
                width: 50px;
                letter-spacing: 5px;
                color: #FFFFFF;
                top: 15px;
                left: -45px;
            }
            
            .butright {
                position: fixed;
                bottom: 0px;
                right: 40%;
                z-index: 9999;
                color: #ffffff;
            }
            
            .image {
                display: block;
                max-width: 750px;
                min-width: 32px;
                width: 100%;
                position: absolute;
                top: 0px;
                left: 0px;
                background: #FFFFFF;
                z-index: 9999;
            }
        </style>
    </head>

    <body>
        <div id="container">
            <div class="container">
                <div class="imge">
                    <img style="width: 100% ; position: absolute;" src="codeimg/code.jpg" />
                    <div class="left state"></div>
                    <div style=" position: absolute;right: 38%; margin-top: 110%;">
                        <div class="bottom">
                            <div class="textbottom">扫码立即注册</div>
                            <div class="codebotom" id="codebotom">
                                <!--<div id="qrcode" class="butright_img"></div>-->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="butright">长按保存图片</div>
        </div>
        <div class="bot" style="position: fixed; z-index: 9999999999999999;"></div>

    </body>
    <!--二维码-->
    <script src="js/jquery.qrcode.logo.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/config.js"></script>
    <script type="text/javascript">
        $(function() {
            var openid_list = eval(decodeURIComponent(localStorage.getItem("openid")))
            var openid = openid_list[1]
            var access_token = openid_list[0]

            window.history.pushState(null, null, "#");
            window.addEventListener('popstate', function(e) {
                window.location.href = 'my.html'
            }, false);
        

            //创建二维码
            /*function createQRCode(id, url, width, height, src) {
                $('#' + id).empty();
                jQuery('#' + id).qrcode({
                    render: 'canvas',
                    text: url,
                    width: width, //二维码的宽度  
                    height: height, //二维码的高度  
                    imgWidth: width / 6, //图片宽
                    imgHeight: height / 6, //图片高
                    src: src //图片中央的二维码
                });
            }
            var url = 'https://api.gzkny.com/h5/aa.html?openid=' + openid;
            createQRCode("qrcode", url, 80, 80, "image/follow.jpg");*/

            /*ios系统dom-to-image方法*/    
            function downloadForJS() {
                domtoimage.toSvg(document.getElementById('container'))
                    .then(function(dataUrl) {
                        /* do something */
                        var img = new Image();
                        img.src = dataUrl;
                        $('.container').hide()
                        //    console.log(dataUrl)
                            console.log('完成')
                        //    document.body.appendChild(img);
                        $('.bot').html(img)
                    });
            }

            /**
             * 将图片转换为base64
             * 解决html2canvas跨域合成失败的问题
             * ios将图片转换为base64
             */
            function getBase64Image(img) {
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
                var dataURL = canvas.toDataURL("image/" + ext);
                return dataURL;
            }

            function ios(img) {
                var image = new Image();
                image.crossOrigin = '';
                image.src = img;
                image.onload = function() {
                    var base64 = getBase64Image(image);
                    console.log(base64);
                    $('.codebotom').html('<img class="butright_img"  src="' + base64 + '"/>')
                }
            }

            //    禁止屏幕滑动
            function bodyScroll(event) {
                event.preventDefault();
            }
            document.body.addEventListener('touchmove', bodyScroll, false);
            $('body').css({
                'position': 'fixed',
                "width": "100%"
            });

            //  获取数据
            $.ajax({
                method: 'GET',
                url: window.BASE_URL + 'wx/accessToken',
                contentType: 'application/x-www-form-urlencoded',
                async: false,
                dataType: "json",
                data: {
                    openid: openid
                },
                success: function(data) {
                    console.log(data)
                    /*ios将图片转换为base64*/
                    ios(data.data.url)
                    // 获取数据
                    $.ajax({
                        method: 'GET',
                        url: window.BASE_URL + 'api/v1/member/get',
                        contentType: 'application/x-www-form-urlencoded',
                        async: false,
                        dataType: "json",
                        data: {
                            access_token: access_token,
                        },
                        success: function(data) {
                            console.log(data)
                            if(data.error == 'success') {
                                $('.state').html(data.data.username)
                                /*ios系统dom-to-image方法*/
                                setTimeout(function() {
                                    downloadForJS()
                                }, 1000)
                            }
                        }
                    });
                }
            });
        })
    </script>

</html>

不是太懂的可以留言

推荐阅读