html2canvas保存为jpeg而无需在浏览器中打开

时间:2013-05-07 21:56:38

标签: javascript jquery html5 html2canvas

我正在尝试创建一个screengrab按钮,用于创建用户document.body的图像。

理想情况下,用户可以选择将图像本地保存为.jpeg

我正在接近使用html2canvas库创建我需要的功能。

function screenGrabber() {
    html2canvas([document.body], {
    logging: true,
    useCORS: true,
    onrendered: function (canvas) {            

        img = canvas.toDataURL("image/jpg");

        console.log(img.length);
        console.log(img);

        window.location.href=img; // it will save locally
    }
});

}

要验证这是否正常,我一直在新的浏览器窗口中打开img变量。图像没有完全呈现,我猜这是因为它的长度超过30,000个字符。

onrendered事件发生后,我怎样才能让用户更好地在本地保存画布?

1 个答案:

答案 0 :(得分:4)

下载程序功能使其更容易:

function download(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";

    //build download link:
    a.href = "data:" + strMimeType + "," + escape(strData);


    if (window.MSBlobBuilder) {
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */



    if ('download' in a) {
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    } /* end if('download' in a) */
    ; //end if a[download]?

    //do iframe dataURL download:
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
} /* end download() */





function screenGrabber() {
    html2canvas([document.body], {
    logging: true,
    useCORS: true,
    onrendered: function (canvas) {            

        img = canvas.toDataURL("image/jpeg");

       download(img, "modified.jpg", "image/jpeg");
    }
});

}