Javascript:图像完成/加载事件未被触发

时间:2017-04-08 12:27:17

标签: javascript image callback

在加载图像之前,我想用这个代码来检查图像的宽高比。

我的问题是没有触发与 image.complete 事件绑定的功能回调。

我哪里错了?

checkAspectRation : function(file){

    var reader = new FileReader();
    /*Read the file*/
    reader.readAsDataURL(file);

    /*Callback */
    reader.onloadend = (function() {

        var image = new Image();

        image.complete = function() {
            // access image size here 
            console.log("Width: " + this.width);
            console.log("Height: " + this.height);
        };

        image.src = reader.result;

        console.log(image);
    });

},

这是加载后图像的值:

enter image description here

[编辑]

我改变了这种方式,但它仍然无法正常工作

checkAspectRation : function(file){

    var image = new Image();
    image.onload = function() {
        // access image size here 
        console.log("Width: " + this.width);
        console.log("Height: " + this.height);
    };

    var reader = new FileReader();

    /*Callback */
    reader.onloadend = (function() {
        console.log(image);
        image.src = reader.result;    
    });

    /*Read the file*/
    reader.readAsDataURL(file);
},

1 个答案:

答案 0 :(得分:0)

解决方案已更改:

main()

var image = new Image();

这很好用:

var image = document.createElement("img");
相关问题