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

Lan
Lan
2023-09-16 / 0 评论 / 166 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年09月16日,已超过432天没有更新,若内容或图片失效,请留言反馈。

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

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

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

评论 (0)

取消