【问题标题】:Why is the image drawn in the canvas when debugging but not when running?为什么调试的时候画在画布上,运行的时候不画?
【发布时间】:2012-02-13 11:25:40
【问题描述】:

我正在学习 HTML5 和 Javascript,我正在尝试在画布上绘制图像。如果我在打破下面标记的行后逐步执行代码,我有以下代码来绘制图像。如果我不调试,则根本不会绘制图像。我究竟做错了什么?带有 FireBug 1.9 的 Firefox 10。

请注意,虽然有一个循环来处理多个图像,但我只选择了一个。我想如果一个不起作用,一百个也不行。 ;-)

<!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>

【问题讨论】:

    标签: javascript html firefox firebug


    【解决方案1】:

    在调用drawImage 方法之前,您必须等到浏览器完全加载图像元素,即使您的图像元素是从base64 字符串而不是从外部文件创建的。所以只需利用图像对象的onload 事件。一个快速的解决方法是这样的:

    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;
    

    【讨论】:

    • 非常感谢达美!有趣的是,答案现在看起来如此明显。 :-)
    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2019-11-12
    • 2019-04-01
    相关资源
    最近更新 更多