从JavaScript中获取变量的返回值

时间:2017-01-24 19:03:37

标签: javascript jquery

我有JavaScript函数检查图像是否为null并调用函数将图像转换为base64字符串,但转换图像后我也无法返回该变量值始终显示undefiend。 updateUserDetails 它的onclick功能,帮我解决它。

var userImgData;
function updateUserDetails() {

   if (userImgData === "undefined") {

        ImgData = (document.getElementById("userProfileImage"));
        getUserBase64Image(ImgData.src)
    }
  updateDetails(userImgData)
}

function updateDetails(userImgData )
{
    //i am calling ajax to update
}

function getUserBase64Image(img) {

var i = img;
var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    img = new Image();
img.onload = function () {
    canvas.width = img.width;
    canvas.height = img.height;

    if (canvas.width > canvas.height) {
        canvas.style.width = "320px";
    } else {
        canvas.style.height = "300px";
    }

    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURl = (canvas.toDataURL('image/jpeg'));
     userImgData = dataURl.replace("data:image/jpeg;base64,", " ")

    return userImgData ;
}
img.src = img;
}

1 个答案:

答案 0 :(得分:0)

onload函数是异步的,您可以使用回调解决此问题,如下所示:

 function updateDetails(customerImgData,CB)
    {
      //i am calling ajax to update
     }

      function getUserBase64Image(img) {

    var i = img;
     var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    img = new Image();
    img.onload = function () {
    canvas.width = img.width;
    canvas.height = img.height;

    if (canvas.width > canvas.height) {
        canvas.style.width = "320px";
    } else {
        canvas.style.height = "300px";
    }

    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURl = (canvas.toDataURL('image/jpeg'));
     userImgData = dataURl.replace("data:image/jpeg;base64,", " ");

     CB(userImgData);

    return userImgData ;
  }
 img.src = img;
}

function updateUserDetails(imageData){
      //you will get image data here in variable "imageData",
      //put your code here.
}

updateUserDetails(customerImgData,updateUserDetails);//function call.