繁体   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