2013-04-25 84 views
1

現在有一點Javascript的噩夢。輸出base64圖像數據到新窗口而不被阻塞?

我使用html2canvas到一個div轉換成畫布,然後.toDataURL畫布轉換爲Base64數據流。

我想在新窗口中打開的base64圖像數據,但它得到通過我測試過的每一個彈出窗口攔截器攔截。

這裏是我的功能

function generateImage(xarg){ 
    var divid= document.getElementById(xarg); 
    html2canvas(divid, { 
     onrendered: function(canvas) { 
      var imgdata = canvas.toDataURL("image/png"); 
      window.open(imgdata); 
     } 
    }); 
} 

任何想法的樣品,爲什麼我的window.open被阻止?

編輯:我得到的另一個想法是啓動圖像的下載,但我發現每個解決方案都需要將數據更改爲image/octet-stream,這會弄亂文件類型,並且我的用戶也不會能夠處理這些問題(尤其是那些在移動設備上)。 我原本有一個更長的帖子來解釋我的情況,但爲了簡潔起見我截斷了它。被封鎖的,因爲它被打開(甚至從一個點擊事件的回調),異步方式對彈出

+0

這是發生在一個'click'事件?或者你是否在其他時間運行它?您是否嘗試用''「替換'imgdata'來查看它是否會打開一個空窗口? – Ian 2013-04-25 05:32:42

+0

我打賭的'onrendered'方法是一個異步之一,所以範圍失去其「點擊」上下文,並因此被阻止通過彈出阻斷劑(像由'window.open'打開其他彈出窗口不是由'click'事件) – Ian 2013-04-25 05:38:37

回答

1

其他直接回應。我身邊工作的問題是: - 直接單擊處理 打開一個空白的彈出窗口 - 啓動html內容 的「canva-ification」 - 創建一個臨時形式的職位,在彈出的canva的base64數據

這種方法的缺點是用戶在Canva生成時有一個空白彈出窗口。我希望這有幫助。

function clickHandler(elementId /*the id of the element to convert to an image */) { 
    // opens the popup directly -> not blocked by browsers 
    var popup = window.open('about:blank', 'screenshotWindow', 'width=950,height=635'); 

    // creates the form 
    var form = window.document.createElement('form'); 
    form.setAttribute('method', 'post'); 
    form.setAttribute('target', 'screenshotWindow'); 
    window.document.body.appendChild(form); 

    html2canvas(window.document.getElementById(elementId), { 
     onrendered: function(canvas) { 
      // posts the base64 content in the popup with the form and removes it 
      form.setAttribute('action', canvas.toDataURL('image/png')); 
      popup.focus(); 
      form.submit(); 
      window.document.body.removeChild(form); 
     } 
    }); 
}