Why is the image drawn in the canvas when debugging but not when running?

北战南征 提交于 2019-12-02 13:16:35

问题


I'm learning HTML5 and Javascript and I'm trying to draw an image on a canvas. I have the following code which draws the image if I step through the code after breaking on the line marked below. If I don't debug then the image is not drawn at all. What am I doing wrong? Firefox 10 with FireBug 1.9.

Note that although there's a loop to handle multiple images, I've only been selecting one. I figure if one doesn't work, a hundred won't work either. ;-)

<!DOCTYPE html>
<html>
<body>
    <input type="file" id="files" name="files[]" multiple />
    <canvas id="picCanvas" />
    <script>
        function handleFileSelect(evt) {
            var files = evt.target.files;

            // Loop through the FileList and render images
            for (var i = 0, f; f = files[i]; i++) {

                // Only process image files.
                if (!f.type.match('image.*')) {
                    continue;
                }

                var reader = new FileReader();

                // Closure to capture the file information.
                reader.onload = (function (theFile) {
                    return function (e) {
                        var img = document.createElement('img'); // <-- BREAK HERE!
                        img.src = e.target.result;

                        var canvas = document.getElementById('picCanvas');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        var ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);
                    };
                })(f);

                // Read in the image file as a data URL.
                reader.readAsDataURL(f);
            }
        }

        document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>
</body>
</html>

回答1:


You have to wait until the image element is fully loaded by the browser before calling the drawImage method, even if your image element is created from a base64 string and not from an external file. So just make use of the onload event of the image object. A quick fix would be like this:

var img = document.createElement('img');

img.onload = function()
{
    var canvas = document.getElementById('picCanvas');
    canvas.width = this.width;
    canvas.height = this.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(this, 0, 0);
}

img.src = e.target.result;


来源:https://stackoverflow.com/questions/9254760/why-is-the-image-drawn-in-the-canvas-when-debugging-but-not-when-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!