htmlcanvas2 傳入節點生成圖片

Shao Mingchen發表於2020-11-13

/**

  • htmlcanvas2 傳入節點生成圖片
    */
    canvas canvas.toDataURL 圖片太大會導致儲存失敗,解析出來的超出了瀏覽器對於url的限制 故使用canvas.toBlob

import html2canvas from ‘html2canvas’;
/**

  • htmlcanvas2 傳入節點生成圖片
  • @param {*} node 節點
    /
    export function captureScreen(node) {
    // 呼叫html2canvas外掛
    html2canvas(node, {
    allowTaint: false,
    foreignObjectRendering: true,
    taintTest: false,
    useCORS: true,//火狐瀏覽器新增項
    }).then(canvas => {
    var image = canvas.toDataURL(“image/png”).replace(“image/png”, “image/octet-stream”);
    var userAgent = navigator.userAgent;
    //判斷是否是IE11
    if (-1 !== userAgent.indexOf(“Trident”)) {
    var arr = image.split(’,’);
    var mime = arr[0].match(/?.
    ?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n–) {
    u8arr[n] = bstr.charCodeAt(n);
    }
    window.navigator.msSaveBlob(new Blob([u8arr], { type: mime }), “download.png”);
    } else {
    canvas.toBlob(function (blob) {
    const eleLink = document.createElement(‘a’);
    eleLink.download = “img.png”;
    eleLink.style.display = ‘none’;
    // 字元內容轉變成blob地址
    eleLink.href = URL.createObjectURL(blob);
    // 觸發點選
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然後移除
    document.body.removeChild(eleLink);
    }, ‘image/png’, 1);
    }
    })
    }

相關文章