html2canvas

作者: nymlc | 来源:发表于2019-01-06 14:40 被阅读0次

    前言

    一旦有了女朋友,人很颓废,加上换了工作,整整半年多未更新,懒得费解

    前提:整个放canvas转成图片的区域

    <div id="view">
    </div>
    

    坑1:滚动截屏
    将目标区域Dom克隆,并设置克隆Dom的狂傲,截图克隆区域即可

    const targetDom = document.querySelector("#admin")
    const copyDom = targetDom.cloneNode(true)
    copyDom.style.width = targetDom.scrollWidth + 'px'
    copyDom.style.height = targetDom.scrollHeight + 'px'
    document.body.appendChild(copyDom)
    html2canvas(copyDom, {
        allowTaint: false,
        useCORS: true,
        height: targetDom.scrollHeight,
        width: targetDom.scrollWidth
    }).then(canvas => {
    // canvas
    });
    

    坑2:截屏区域有跨域图片
    若是百度会发现修改源码是最多的。其实那是老版本,新版本(1.x)只要配下参数即可即:

    // allowTaint: false   不允许跨域图片污染画布
    // useCORS: true   允许加载跨域图片
    

    坑3:下载图片
    移动端不好整,PC端就简单了

    // 插入之前canvas下
    html2canvas(copyDom, {
                        allowTaint: false,
                        useCORS: true,
                        height: targetDom.scrollHeight,
                        width: targetDom.scrollWidth
                    }).then(canvas => {
                        this.printShow = true
                        copyDom.parentNode.removeChild(copyDom)
                        // console.log(canvas.style.width)
                        canvas.style.width = parseFloat(canvas.style.width) * 0.8 + 'px'
                        canvas.style.height = parseFloat(canvas.style.height) * 0.8 + 'px'
                        setTimeout(() => {
                            const container = document.querySelector('#view')
                            while (container.hasChildNodes()) {
                                container.removeChild(container.firstChild)
                            }
                            // toImage
                            const dataImg = new Image()
                            dataImg.src = canvas.toDataURL('image/png')
                            document.querySelector('#view').appendChild(dataImg)
    
                            const alink = document.createElement("a");
                            alink.href = dataImg.src;
                            alink.download = "testImg.jpg";
                            alink.click();
                        }, 0)
                    });
    

    相关文章

      网友评论

        本文标题:html2canvas

        本文链接:https://www.haomeiwen.com/subject/kkssrqtx.html