js实现canvas保存图片为png格式并下载到本地

js

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);
}

html

<button onclick="exportCanvasAsPNG('pieChart','nianling')">保存</button>

 

posted @ 2021-08-28 00:14  木子欢儿  阅读(665)  评论(0编辑  收藏  举报