使用html2canvas.js将HTML生成图片

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../script/jquery-1.9.1.min.js"></script>
    <script src="../script/html2canvas.js"></script>
    <style type="text/css">
        .divBody {
            position: absolute;
            width: 100%;
            height: 100%;
            background: url(../images/bg.jpg) no-repeat center top;
            background-size: 100% 100%;
            font-family: "黑体";
            color: #292929;
            letter-spacing: 2px;
            z-index: 1000;
        }

        .divInfo {
            width: 76%;
            margin-left: 12%;
            position: relative;
            top: 25%;
            text-align: center;
        }
        #btnDown{
            position:absolute;
            top:15px;
            right:10px;
            z-index:1000;
            cursor: pointer;
        }

    </style>
</head>

<body>
    <div id="divBody" class="divBody">
        <div class="divInfo" id="divInfo">
            <h1>剑来语录</h1>
            <div>
                <p>我住人间万古宅,大日高升在墙东。</p>
                <p>睁眼便觉扰清梦,敕令明月坠其中。</p>
                <p>天上仙佛三百万,遇我也须称上神。</p>
                <p>醉乘白鹿驾青虬,列仙遇我求醇酒。</p>
                <p>挂冠天宫桂枝上,手抓金乌做炭笼。</p>
                <p>悲哉仙人千秋梦,一梦见我误长生。</p>
            </div>
        </div>
    </div>
    <div id="btnDown">
        <img src="../images/share.png" style="width:2rem;height:2rem;" />
    </div>
</body>

</html>
<script type="text/javascript">
    $(function () {
        $("#btnDown").click(function () {
            downPNG("下载图片.png", "divBody");
        });
    });

    function downPNG(pngName, pngId) {
        var scaleBy = getDPR();//获取像素比

        var canvas = document.createElement('canvas');// 创建自定义 canvas 元素
        // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
        var width = document.getElementById(pngId).clientWidth;
        var height = document.getElementById(pngId).clientHeight;

        canvas.width = width * 2;
        canvas.height = height * 2;

        var context = canvas.getContext('2d');
        // 将所有绘制内容放大像素比倍
        context.scale(2, 2);
        var rect = document.getElementById(pngId).getBoundingClientRect(); //获取元素相对于视察的偏移量
        context.translate(-rect.left, -rect.top); //设置context位置,值为相对于视窗的偏移量负值,让图片复位

        html2canvas(document.getElementById(pngId), {
            canvas,
            dpi: 300,
            scale: 1,
            useCORS: true, //(图片跨域相关)
            allowTaint: false, //允许跨域(图片跨域相关)
            onrendered: function (imgCanvas) {
                var imgData = imgCanvas.toDataURL('image/octet-stream');
                if (imgCanvas.msToBlob) { // IE 9+浏览器
                    var blob = imgCanvas.msToBlob();
                    window.navigator.msSaveBlob(blob, pngName);
                } else {
                    saveFile(imgData, pngName);
                }
            }
        });
    }

    function saveFile(data, filename) {
        
        //微信浏览器不能直接下载图片,需要展示一张图片长按下载...        
        if (is_weixn()) {
            //方法一
            var img = document.createElement('img');
            img.src = data;
            img.style.width = "100%";
            $("#divBody").html(img);

            //方法二
            // var html = "<img src ='" + data + "' style='width:100%;height:100%' />";
            // $("#divBody").html(html);

            $("#btnDown").hide();//隐藏分享按钮

            alert("图片生成成功,长按保存图片!");//提示用户长按下载图片
        } else {
            console.log(1);
            //直接下载图片
            var save_link = document.createElement('a');
            save_link.href = data;
            save_link.download = filename;
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            save_link.dispatchEvent(event);
        }
        

        

        
    };

    function getDPR() {
        if (window.devicePixelRatio && window.devicePixelRatio > 1) {
            return window.devicePixelRatio;
        }
        return 2;
    }

    function is_weixn() {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true;
        } else {
            return false;
        }
    }

</script>

  

上一篇:使用jspdf和html2canvas将当前网页保存为pdf


下一篇:VUE html2Canvas截取页面内容生成pdf(直接扒直接用爽的一匹)