2017-04-08 117 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

另外,我是否真的需要轉換圖像?如果我只是使用原始圖像源,可以嗎? –

相關問題