Quick Print HTML5 Canvas

I found that the first time I printed, the canvas was blank. I added an event listener to wait until the image/document is loaded. Now the canvas is ready to print each time. Here's the code which is working for me:

const dataUrl = document.getElementById('the-pdf-canvas').toDataURL(); 

let windowContent = '<!DOCTYPE html>';
windowContent += '<html>';
windowContent += '<head><title>Print canvas</title></head>';
windowContent += '<body>';
windowContent += '<img src="' + dataUrl + '">';
windowContent += '</body>';
windowContent += '</html>';

const printWin = window.open('', '', 'width=' + screen.availWidth + ',height=' + screen.availHeight);
printWin.document.open();
printWin.document.write(windowContent); 

printWin.document.addEventListener('load', function() {
    printWin.focus();
    printWin.print();
    printWin.document.close();
    printWin.close();            
}, true);

Use printJS and this one liner:

printJS({printable: document.querySelector("#your-canvas").toDataURL(), type: 'image', imageStyle: 'width:100%'});

I have searched alot and found a solution which works perfectly :) Used onclick event

function printCanvas()  
{  
    var dataUrl = document.getElementById('anycanvas').toDataURL(); //attempt to save base64 string to server using this var  
    var windowContent = '<!DOCTYPE html>';
    windowContent += '<html>'
    windowContent += '<head><title>Print canvas</title></head>';
    windowContent += '<body>'
    windowContent += '<img src="' + dataUrl + '">';
    windowContent += '</body>';
    windowContent += '</html>';
    var printWin = window.open('','','width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
    printWin.document.close();
    printWin.focus();
    printWin.print();
    printWin.close();
}