image onload event triggering before its image fully loaded?

廉价感情. 提交于 2019-12-08 12:52:29

问题


I am using Jcrop jquery plugin, and triggering the initJcropBox() function on onload event.

but this function is being triggered before the image is fully loaded. which is causing problem. such as showing incorrect size of jcropbox or not showing jcropbox at all.

when i place a line, it works fine. but is not a solution. setTimeout('initJcropBox()',2000);

How can I trigger initJcropbox() function after image is fully loaded/rendered in the browser?

  var api;

     function initJcropBox(){
      api = $.Jcrop('#cropbox',{
          bgColor: 'black',
          bgOpacity: .7,
          onSelect: updateCoords,
          onChange: updateCoords,
          boxWidth: 400
      });
        api.animateTo([0,0,$('#cropbox').width(),$('#cropbox').height()]);
    }     

    function insertImage(name) {
        var img = new Image();
        img.onload = initJcropBox;
        img.src = name;
        img.id = 'cropbox';

        return img;
    }

$('td.imageFile').live('click', function(e){
    fileWithPath = "uploads/original/" + $(this).text();
    $('#cropbox').remove();
    $("#cropcontainer").empty().html(insertImage(fileWithPath));
});

回答1:


Just google it, I sort this problem myself. here is the working solution

function insertImage(name) {

  var img = new Image();
  img.id = 'cropbox';
  img.src = name;

  if(img.complete) setTimeout('initJcropBox()', 500);   
  else onload= initJcropBox;  

  return img;
 }



回答2:


Try replacing your insertImage(name) function with that. This should trigger the load event on the image until it's truly loaded.

function insertImage(name) {
    var img = $('<img id="cropbox" />');
    img.load(function(){ 
                if (! this.complete) {
                  return false;
                  $(this).load();
                }

                else if (typeof this.naturalWidth != 'undefined' && this.naturalWidth == 0) {
                  return false;
                  $(this).load();
                }
                else
                  initJcropBox();
             })
        .attr('src',name);
    return img;
}

I didn't tested it, so let me know if it's worth.




回答3:


Some time ago I had a similar issue. Use load() to load the image and to trigger a callback function. Here are more details.



来源:https://stackoverflow.com/questions/4077890/image-onload-event-triggering-before-its-image-fully-loaded

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