简体   繁体   English

HTML画布不会绘制图像

[英]HTML Canvas Will Not Draw Image

Okay, I know that there are loads of subjects that look identical to this one on SO, but none of them have fixed my issue... 好的,我知道在SO上有很多与此主题相同的主题,但是它们都没有解决我的问题...

I'm trying to grab an image from a file input and throw it onto a canvas so that I can later turn it into a base-64 image... But I've hit a snag in the process that I was not expecting, in drawing the image to the canvas... 我正在尝试从文件输入中抓取图像并将其扔到画布上,以便以后可以将其转换为基于64位的图像...但是我在意料之外的过程中遇到了麻烦,在将图像绘制到画布上...

Taking the following HTML: 采用以下HTML:

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

And the following script: 和以下脚本:

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');
}

The problem I'm having is that the image simply refuses to draw onto the canvas. 我遇到的问题是图像只是拒绝在画布上绘制。 Even going into the console and drawing the image to the canvas manually, after the script has run, it still refuses to draw. 即使进入控制台并手动将图像绘制到画布上,脚本运行后,它仍然拒绝绘制。 Because of this, the image data simply runs through as data:, 因此,图像数据只是作为data:,运行data:,

It's an https site, if that affects anything. 这是一个https网站,如果有影响的话。

For clarification, here's my question: 为了澄清,这是我的问题:

Why is the canvas refusing to render this image? 为什么画布拒绝渲染此图像? How can I fix this issue? 如何解决此问题?

If the intent is to convert the image to Data-URI ("base64"), the FileReader can be used - no need for canvas (which can also alter the image/final compression): 如果要将图像转换为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