Search code examples
javascripthtmlcanvashtml2canvas

html2canvas does not produce toDataUrl() to convert to base64


I am using the below library to convert my html div to canvas.

https://html2canvas.hertzen.com/

Things are working as expected. Now what I want is basically, instead of downloading(which is available via saveAsPNG() method), I want to send the data to server. Now its known that that we need to convert the same to make that happen using toDataUrl(), which converts to a base64.

Using this method toDataUrl(), says, not a function.

Below is the snippet

html2canvas(document.querySelector("#canvasTxt")).then(canvas => {
    console.log(canvas);   //---1
    console.log(canvas.toDataUrl('image/png')); //---2
    console.log(canvas[0].toDataUrl('image/png')); //----3
}); 

1) gives the output as canvas

2) canvas.toDataUrl is not a function

3) canvas[0] is undefined --so I assume no nodelist

So Is there a way to do the conversion using the library ? As I want to send the converted image to server without allowing downloading.

Any help would be appreciated!


Solution

  • Typo: toDataURL URL all caps.

    html2canvas(document.body).then(canvas => {
        console.log(canvas.toDataURL('image/png'));
    });