2017-04-08 42 views
0

我是混合(Cordova)移动应用程序开发人员,我的要求是将GIF图像分享到各种社交媒体平台。我写了一个函数将我的图像转换为Base64数据url。大多数情况下它会转换图像并使分享流畅,但有时,它无法在点击分享按钮时分享图像。有时它不打开共享窗口。我怀疑它转换图像需要多长时间。下面是我的示例代码:使用JavaScript将GIF图像转换为Base64数据uri时的性能问题

function convertFileToDataURLviaFileReader(url, callback) { 
    var xhr = new XMLHttpRequest(); 
    xhr.responseType = 'blob'; 
    xhr.onload = function() { 
     var reader = new FileReader(); 
     reader.onloadend = function() { 
      callback(reader.result); 
     } 
     reader.readAsDataURL(xhr.response); 
    }; 
    xhr.open('GET', url); 
    xhr.send(); 
} 

这是怎样的函数被调用:

//The below function will be called on click of share buttons 

function showSnackBar(e) { 
    imgSource = null; 
    selectedImgId = null; 
    imgDataURL = null; 
    var x = document.getElementById("snackbar"); 
    imgSource = e.target.currentSrc; 
    selectedImgId = e.target.id; 
    x.className = "show"; 
    setTimeout(function() { 
     x.className = x.className.replace("show", ""); 
    }, 3000); 
    //calling function to Convert ImageURL to DataURL 
    convertFileToDataURLviaFileReader(imgSource, function (base64Img) { 
     imgDataURL = base64Img; 
    }); 
    $("#btnShare").click(function (e) { 
     if(imgDataURL != null) { 
      window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null) 
     } 
    }) 
}; 

回答

0

尝试设置变量,如果转换尚未完成,然后运行该份额对话的一次转换已完成(请注意使用下面的变量openShare):

function showSnackBar(e) { 
    imgSource = null; 
    selectedImgId = null; 
    imgDataURL = null; 
    var x = document.getElementById("snackbar"); 
    imgSource = e.target.currentSrc; 
    selectedImgId = e.target.id; 
    x.className = "show"; 
    setTimeout(function() { 
     x.className = x.className.replace("show", ""); 
    }, 3000); 

    var openShare = false; 
    //calling function to Convert ImageURL to DataURL 
    convertFileToDataURLviaFileReader(imgSource, function (base64Img) { 
     imgDataURL = base64Img; 
     if(openShare){ 
      openShare = false; 
      window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null); 
     } 
    }); 

    $("#btnShare").click(function (e){ 
     if(imgDataURL != null) { 
      window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null) 
     }else{ 
      openShare = true; 
     } 
    }); 
}; 
+0

这是打开多个共享窗口@femi。窗口计数从1,2,3,4 ...依次增加.... –

+0

另外,我是否真的需要转换图像?如果我只是使用原始图像源,可以吗? –