Recently I was working on a project where I needed to upload a file in a single page application, so form submission to a backend file was out of the question.
There is also option of uploading files directly with ajax but the backend guy asked me if I can send files in Base64 format.
I knew I can convert image into Base64 by loading it in canvas this way.
But the issue here is that image takes some time to load, resulting in the wrong Base64 string. Fortunately, we have an event for image load completion which we can use to ensure that our image has completely loaded before we draw it into canvas.
The changed code.
Finally decided to convert the code into a generic function that can be invoked any time to do the conversion for us.
We can use it this way.
Also I added a check in function to make sure the load event fires for cached images too.
Later I found out that we can also use FileReader API to read the file and convert into the Base64 format.