为什么我无法预览inputfield上传的图片并在画布中显示?

时间:2018-02-08 14:11:13

标签: javascript html canvas

我需要上传图片并在浏览器的画布中显示。我第一次上传此图片时,画布宽度和高度为零,但第二次图像正确显示?为什么呢?

function previewFile() {
        const canvas = document.getElementById('canvas');
        const img = document.createElement('img');
        const file = document.querySelector('input[type=file]').files[0];
        const reader = new FileReader();
      
        reader.addEventListener("load", function () {
            img.src = reader.result;
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
        }, false);
      
        if (file) {
          reader.readAsDataURL(file);
        }
    }   

 
           <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="./script.js"></script>
        <title>Document</title>
    </head>
    <body>
        <input type="file" onchange="previewFile()"><br>
        <canvas id="canvas"></canvas>
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

当您设置图像src时,它不会同步加载,因此您必须等待图像加载事件,然后才能在画布上绘制它。

JS中与资源相关的许多操作具有异步性,因此您必须处理它。

&#13;
&#13;
function previewFile() {
        const canvas = document.getElementById('canvas');
        const img = document.createElement('img');
        const file = document.querySelector('input[type=file]').files[0];
        const reader = new FileReader();
      
        reader.addEventListener("load", function () {
            img.src = reader.result;
            img.onload = function() {
                canvas.width = img.width;
                canvas.height = img.height;
                canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
            }
        }, false);
      
        if (file) {
          reader.readAsDataURL(file);
        }
    }   

 
&#13;
           <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="./script.js"></script>
        <title>Document</title>
    </head>
    <body>
        <input type="file" onchange="previewFile()"><br>
        <canvas id="canvas"></canvas>
    </body>
    </html>
&#13;
&#13;
&#13;