js 通过html2canvas实现网页截图

js yekong

vue外包的h5页面,客户要求点击按钮可以将整个页面生成一张图片。这里我们通过html2canvas方法来实现。
js 实现网页截图

实现代码

<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script>
    document.getElementById("export").addEventListener('click', function () {
        //创建一个新的canvas
        document.documentElement.scrollTop = 0
        window.pageYOffset = 0
        document.body.scrollTop = 0
        var canvas2 = document.createElement("canvas");
        let canvasObj = document.querySelector('.viewport');
        var w = parseInt(window.getComputedStyle(canvasObj).width);   //获取目标元素的宽高
        var h = parseInt(window.getComputedStyle(canvasObj).height);
        //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
        var context = canvas2.getContext("2d");
        context.scale(2, 2);
        canvas2.width = w;
        canvas2.height = h;
        html2canvas(document.querySelector('.viewport'), {canvas: canvas2}).then(function (canvas) {
            let image = new Image();
            image.className = "newImg"
            image.src = canvas.toDataURL("image/png");
            document.body.appendChild(image)
        });
    });

</script>

演示地址:

点击按钮当前页面截屏

喜欢