Home > OS >  Javascript convert uploaded image to canvas.toDataURL()
Javascript convert uploaded image to canvas.toDataURL()

Time:06-10

I need the data url of the image to be in:

 'data:image/jpeg;base64,""'.

format

So my first solution is to render the uploaded image as an Image element, and use canvas.drawImage(imageElement), to get canvas.toDataURL(), but I'm getting the canvas has been tainted Error.

Curious is there any alternative way to get the data url of the uploaded image?

Thanks.

CodePudding user response:

You don't need a canvas. You can just use the File API.

const element = document.getElementById('file');
element.addEventListener('change', ({target: {files}}) => {
  const [image] = files;
  const reader = new FileReader();
  reader.onload = ({target: {result}}) => console.log(result);
  
  reader.readAsDataURL(image);
});
<input id="file" type="file">

  • Related