屏幕截图功能

时间:2022-05-09 06:04:49

直接上代码

<!DOCTYPE html>
<html>
<head>
    <meta name="layout" content="main">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script type="text/javascript" src="./jquery.js"></script> //自己找来加上
    <script type="text/javascript" src="./html2canvas.js"></script> //自己找来加上

    <script type="text/javascript">
        function printById() {
            var img = new Image();
            img.crossOrigin = "Anonymous";
            var canvas2 = document.createElement("canvas");
            let _canvas = $("body")[0];
            var w = parseInt(window.getComputedStyle(_canvas).width);
            var h = parseInt(window.getComputedStyle(_canvas).height);
            //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
            canvas2.width = w * 4;
            canvas2.height = h * 4;
            canvas2.style.width = w + "px";
            canvas2.style.height = h + "px";
            //可以按照自己的需求,对context的参数修改,translate指的是偏移量
            var context = canvas2.getContext("2d");
            context.scale(2, 2);
            html2canvas($("body")[0], {  选择哪个盒子里面的截图就改成哪个盒子的dom
                useCORS: true,
                logging: true,
                taintTest: true
            }).then(canvas => {
                console.log("-----picture----");
            //   var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
            var imgUri = canvas.toDataURL("image/png");
            $(".bg").html(
                "<img style='width: 100%;height: 100%;' src='" + imgUri + "'/>"
            );
        });
        }
    </script>
</head>
<body>

Hello!
<div class="" style="background-color: #abc;" id='myPrint'>
    计算机天堂测试html5页面截图
    <br>jsjtt.com
</div>

<textArea id="textArea" col="20" rows="10" ></textArea>
dddddd
<a href="javascript:void(0)" onclick="printById()">打印</a>
生成界面如下:
<div class="bg"></div>
</body>
</html>