簡體   English   中英

HTML畫布不會繪制圖像

[英]HTML Canvas Will Not Draw Image

好的,我知道在SO上有很多與此主題相同的主題,但是它們都沒有解決我的問題...

我正在嘗試從文件輸入中抓取圖像並將其扔到畫布上,以便以后可以將其轉換為基於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:,運行data:,

這是一個https網站,如果有影響的話。

為了澄清,這是我的問題:

為什么畫布拒絕渲染此圖像? 如何解決此問題?

如果要將圖像轉換為Data-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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM