0

I want convert a picture to base64. So, in the html i put a img and canvas with display:none

html :

<img style="display:none" id="imgDownload" />
<canvas style="display:none" id="myCanvas" />

and in the controller i do this :

controller :

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("imgDownload");
img.crossOrigin = 'anonymous';
img.src = conf.storeUrl + '/' +$scope.fRoot.name + $scope.getFileWay() + value.name;
console.log(img);
ctx.drawImage(img, img.naturalHeight, img.naturalWidth);
var base64Img = c.toDataURL();

i get a base64 but it's not good...

see an example :

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAxUlEQVR4nO3BMQEAAADCoPVPbQhfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOA1v9QAATX68/0AAAAASUVORK5CYII=

you can test it here.

and i tried giving a height and width to the canvas but the result is that :

data:,

and it's the same thing for différents images, you have a idea?

Thibaud Ledeux
  • 43
  • 1
  • 10

1 Answers1

0

You're trying to draw the image on the canvas before it has finished loading.
After setting img.src, it takes some time to load the image, so you have to wait until that has happened before you proceed.
You can use img.onload for that:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("imgDownload");
img.crossOrigin = 'anonymous';
img.onload = function()
{
    console.log(img);
    ctx.drawImage(img, img.naturalHeight, img.naturalWidth);
    var base64Img = c.toDataURL();
};
img.src = conf.storeUrl + '/' +$scope.fRoot.name + $scope.getFileWay() + value.name;
Siguza
  • 21,155
  • 6
  • 52
  • 89