2016-12-02 85 views
0

好吧,我知道有一些看起來與這一項上SO科目負荷,但他們都沒有固定我的問題......HTML畫布不會畫圖片

我試圖抓住一個圖像從一個文件輸入並將其放到一個畫布上,以便我可以稍後將其轉換爲一個base-64圖像......但是,在將圖像繪製到畫布上時,我遇到了一個我並不期待的過程中的障礙...

採取以下HTML:

<input type="file" id="fileIn" onchange="preview()"><br> 
<img id="filePreview"><br> 
<canvas id="fileCanvas"></canvas> 

而且下面的腳本:

var dataurl = ''; 
function preview(){ 
    document.getElementById('filePreview').src = URL.createObjectURL(document.getElementById('fileIn').files[0]); 
    document.getElementById('filePreview').onload = showInCanvas; 
    cnv = document.getElementById('fileCanvas'); 
    ctx = cnv.getContext('2d'); 
} 
function showInCanvas(){ 
    cnv.style.width = document.getElementById('filePreview').naturalWidth + 'px'; 
    cnv.width = document.getElementById('filePreview').naturalWidth; 
    cnv.style.height = document.getElementById('filePreview').naturalHeight + 'px'; 
    cnv.height = document.getElementById('filePreview').naturalHeight + 'px'; 
    ctx.clearRect(0, 0, cnv.width, cnv.height); 
    ctx.drawImage(document.getElementById('filePreview'), 0, 0); 
    dataurl = cnv.toDataURL('image/png'); 
} 

我遇到的問題是圖像只是拒絕畫在畫布上。即使進入控制檯並手動將圖像繪製到畫布上,腳本運行後,它仍然拒絕繪製。正因爲如此,圖像數據簡單地貫穿爲data:,

這是一個https網站,如果這影響了任何東西。

爲了澄清,我的問題是:

爲什麼帆布拒絕使這個形象?我該如何解決這個問題?

+0

數據的URI已經Base64編碼,所以你的'URL.createObjectURL'應該是所有你需要(假設它的工作原理)。 –

+0

,如果它不,你需要顯示該代碼。您的問題需要包含重新創建問題所需的所有代碼。 –

+0

糟糕,我在那裏留下了一些document.getElementById的簡寫。應該現在出來。我只是把它全部(在帖子中的代碼)放到HTML編輯器中,並得到了完全相同的結果... –

回答

1

如果目的是將圖像數據的URI(「BASE64」)進行轉換,該FileReader可以使用 - 無需畫布(其也可以改變圖像/最後的壓縮):

fileIn.onchange = function(e) { 
 
    var fr = new FileReader(); 
 
    fr.onload = done.bind(fr); 
 
    fr.readAsDataURL(e.target.files[0]); 
 
} 
 

 
function done() { 
 
    var dataURI = filePreview.src = this.result; 
 
    alert(dataURI.substr(0, 35) + "...") 
 
}
<input type="file" id="fileIn"><br> 
 
<img id="filePreview"><br> 
 
<canvas id="fileCanvas"></canvas>

+0

像魅力一樣工作,並刪除了畫布依賴項。很棒! –