JavaScript method to download a HTML5 Canvas as png

Tue, 20 March 2018

function.js
function downloadCanvasAsPng(elementId, file_name) {
    var canvas = document.getElementById(elementId);
    var dataURL = canvas.toDataURL('image/png');
    dataURL = dataURL.replace(/^data:image\\/\\w+;base64,/, '');
    var link = document.createElement('a');
    link.setAttribute('style', 'position:fixed;left-10000px;');
    link.setAttribute('href', 'data:application/octet-stream;base64,' + dataURL);
    link.setAttribute('download', file_name + '.png');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}