js下载网站中的canvas保存为图片

2023-09-16 08:31:12 浏览数 (4)

用处挺大的,毕竟很多生成网站都是生成canvas,懂得都懂

代码语言:javascript复制
function exportCanvasAsPNG(id, fileName) {

    var canvasElement = document.getElementById(id);

    var MIME_TYPE = "image/png";

    var imgURL = canvasElement.toDataURL(MIME_TYPE);

    var dlLink = document.createElement('a');
    dlLink.download = fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
}

直接通过jspath获取element

代码语言:javascript复制
var canvasElement = document.querySelector("#root > div > div > div > div > div.NewPatternView_preview__2qc3i > div > canvas");
var MIME_TYPE = "image/png";
var imgURL = canvasElement.toDataURL(MIME_TYPE);
var dlLink = document.createElement('a');
dlLink.download = 'a.png';
dlLink.href = imgURL;
dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

document.body.appendChild(dlLink);
dlLink.click();
document.body.removeChild(dlLink);

0 人点赞