2016-12-02 88 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

像魅力一样工作,并删除了画布依赖项。很棒! –