Assim, o alerta fornece valores indefinidos para a largura e a altura. Eu acho que os valores w e h da imagem do cálculo img.onload não estão sendo passados para os valores a serem retornados, ou podem estar retornando w e h antes que o onload os calcule:
function getMeta(url){ var w; var h; var img=new Image; img.src=url; img.onload=function(){w=this.width; h=this.height;}; return {w:w,h:h} } // "http://sofpt.miximages.com/width/mootools_83_snookca.png" //1024x678 // "http://sofpt.miximages.com/width/github.png" //128x128 var end = getMeta("http://sofpt.miximages.com/width/github.png"); var w = end.w; var h = end.h; alert(w+'width'+h+'height');
Como posso fazer o alerta mostrar a largura e a altura corretas?
http://jsfiddle.net/YtqXk/
function getMeta(url){ $("
",{ load : function(){ alert(this.width+' '+this.height); }, src : url }); }
function getMeta(url){ var img = new Image(); img.onload = function(){ alert( this.width+' '+ this.height ); }; img.src = url; }
function getMeta(url){ var img = new Image(); img.addEventListener("load", function(){ alert( this.naturalWidth +' '+ this.naturalHeight ); }); img.src = url; }
Use o acima simplesmente como: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
Basta passar um retorno de chamada como argumento como este:
function getMeta(url, callback) { var img = new Image(); img.src = url; img.onload = function() { callback(this.width, this.height); } } getMeta( "http://sofpt.miximages.com/width/mootools_83_snookca.png", function(width, height) { alert(width + 'px ' + height + 'px') } );
As variables w
e h
na function img.onload
não estão no mesmo escopo com as da function getMeta()
. Uma maneira de fazer isso é a seguinte:
Violino : http://jsfiddle.net/ppanagi/28UES/2/
function getMeta(varA, varB) { if (typeof varB !== 'undefined') { alert(varA + ' width ' + varB + ' height'); } else { var img = new Image(); img.src = varA; img.onload = getMeta(this.width, this.height); } } getMeta("http://sofpt.miximages.com/width/mootools_83_snookca.png");
ES6: Usando async/await
você pode fazer isso de forma sequencial
async function getMeta(url) { return new Promise((resolve, reject) => { let img = new Image(); img.onload = () => resolve(img); img.onerror = reject; img.src = url; }); }
E você pode usá-lo da seguinte forma (que é quase idêntico ao código em sua pergunta (eu adiciono await
palavra-chave e alterar a variável end
para img
e alterar var
para let
palavra-chave)
let img = await getMeta("http://sofpt.miximages.com/width/github.png"); let w = img.width; let h = img.height; alert(w+'width'+h+'height');
lembre-se que se você chamar getMeta
em alguma function, ele deve ter a palavra async
chave async
em sua definição.