html2canvas下载

方法一:

<div id="shadow"></div>
 // 下载证书
    function download() {
        console.log('下载')
        html2canvas(document.querySelector("#shadow")).then(canvas => {
            document.body.appendChild(canvas)
            let imageURL = canvas.toDataURL("image/png");  
            canvas转base64图片
            console.log(imageURL);
           saveImage(imageURL,'名字')

        });
    }      

 /**
     *将base64赋值到a标签并下载截图
     * @param data base64图片字符串
     * @param filename 下载截图名称
     */
    function saveImage(data, filename) {
        let saveLink = document.createElement('a');
        saveLink.style = "display: none";
        saveLink.href = data;
        saveLink.download = filename;
        let event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        saveLink.dispatchEvent(event);
        setTimeout(()=>function(){
            document.body.removeChild(saveLink);//保存完后删除临时a节点
        },200);
    }  

方法二:

<div id="shadow"></div>
// 下载证书
    function download() {
        console.log('下载')
        html2canvas(document.querySelector("#shadow")).then(canvas => {
            convertCanvasToImg(canvas)
        });
    }
//转换图片格式
    function convertCanvasToImg(canvas) {
        // canvas base64 转 blob
        var myBlob = dataURLtoBlob(canvas.toDataURL('img/png', 0.92))
        // blob转URL对象
        myUrl = URL.createObjectURL(myBlob)
        // 创建a标签,下载图片
        downImg(myUrl)
    }
    //base64 转 blob
    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }

    //下载图片 filename是图片名称
    function downImg(url) {
        // 创建a标签 并设置其相关属性,最后触发其点击事件
        let a = document.createElement("a")
        let clickEvent = document.createEvent("MouseEvents");
        a.setAttribute("href", url)
        a.setAttribute("download", "证书")
        a.setAttribute("target", '_blank')
        a.setAttribute("width", '100px')
        a.setAttribute("height", '100px')
        clickEvent.initEvent('click', true, true)
        a.dispatchEvent(clickEvent);
    }

 注:如果有背景图片请用png格式的

posted @ 2023-06-02 11:11  挽你手  阅读(413)  评论(0编辑  收藏  举报