2009-10-29 13 views
16

image naturalWidth return zero ... to wszystko, dlaczego?image naturalWidth return zero

var newimage = new Image(); 
newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
var width = newimage.naturalWidth; 
alert (width); 

POMOC, nie wiem dlaczego!

*** ta ścieżka jest dobra, obraz się wyświetla!

Odpowiedz

34

Przypuszczam, że to dlatego, że nie czekasz na załadowanie obrazu - spróbuj tego:

var newimage = new Image(); 
newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
newimage.onload = function() 
{ 
    var width = this.naturalWidth; 
    alert(width); 
} 
+5

Kolejność, w jakiej '' onload' src' i są ważne dla wywołania zwrotnego obciążenia, aby sprawdził. –

+0

Hmm Testowałem w przeglądarce Chrome i Firefox i oboje działali poprawnie. IE pokazał również alert, ale nie obsługuje funkcji naturalWidth – Greg

+0

Dziękuję bardzo! Działa jak wdzięk –

0

W naturalWidth i naturalHeight właściwości nie są obsługiwane w IE, więc dać this fix spróbować.

+0

co powiesz na "normalną" szerokość i wysokość – menardmam

2

Oto kod FINAL PRACY .... w przypadku kogoś whant wiedzieć, że wszystko jest kwestią wainting mieć wszystkie obrazy załadowane! ...

<script type="text/javascript"> 

$ (function() { $ ("# kciuk") jCarouselLite ({ btnNext: "#down" btnPrev: "#UP", pionowy: true, widocznych: 4 });

$("#thumb li img").click(function() { 

    var newlinkimage = $(this).attr("src"); 
    newlinkimage = 'retouche-hr' + newlinkimage.substring(14,17); 

    $('#hr').remove(); 

    var newimage = new Image(); 
    newimage.src = newlinkimage + '-a.jpg'; 

    newimage.onload = function() 
    { 
     var width = (newimage.width); 
     var height = (newimage.height); 

     $('#contentfull').append('<div id="hr"> </div>'); 
     $("#hr").attr("width", width).attr("height", height); 
     $("#hr").addClass('hrviewer'); 
     //alert('a'); 
     $("#hr").append('<div id="avant"> <img alt="before" src="' + newlinkimage +'-a.jpg"></div>'); 
     $("#hr").append('<div id="apres"> <img alt="after" src="' + newlinkimage +'-b.jpg"></div>'); 
     //alert('b'); 
     $("#avant img").attr("src", newlinkimage + '-a.jpg').attr("width", width).attr("height", height); 
     $("#apres img").attr("src", newlinkimage + '-b.jpg').attr("width", width).attr("height", height); 

     $("#apres img").load(function(){$("#hr").beforeAfter({animateIntro:true});}); 

    } 

}) 

. });

0

Dla mnie następujące prace ...

$('<img src="mypathtotheimage.png"/>').load(function() { 

     if (!isNotIe8) { 
      // ie8 need a fix 
      var image = new Image(); // or document.createElement('img') 
      var width, height; 
      image.onload = function() { 
       width = this.width; 
       height = this.height; 
      }; 
      image.src = $(this).attr("src"); 

     } else { 
      // everythings fine here .... 
      // this.naturalWidth/this.naturalHeight; 
     }