2012-02-03 14 views
5

En la etiqueta de imagen, si no proporcionamos propiedades de ancho y alto, no obtendremos nada al recuperar el ancho y el alto de la imagen. Estoy usando el elemento canvas para cargar una imagen y escalar proporcionalmente. Para hacer esto, tengo que obtener el tamaño real de la imagen. ¿Es posible hacer eso en html 5?¿Podemos obtener el tamaño real de la imagen a través del lienzo?

Respuesta

0

No entendí completamente su pregunta.

Pero puede usar javascript para obtener el ancho y alto de la imagen.

y luego pasarlo a

/Five arguments: the element, destination (x,y) coordinates, and destination 
// width and height (if you want to resize the source image). 
context.drawImage(img_elem, dx, dy, dw, dh); 

mientras dibuja la imagen sobre lienzo.

o comprobar esto si ayuda

http://jsfiddle.net/jjUHs/

1

si he entendido bien, puede utilizar el método getComputedStyle.

var object = document.getElementById(el); 
var computedHeight = document.defaultView.getComputedStyle(object, "").getPropertyValue("width"); 
6

El HTMLImageElement tiene dos propiedades para esto, naturalWidth y naturalHeight. Usa esos.

Como en:

var img = new Image(); 

img.addEventListener('load', function() { 
    // once the image is loaded: 
    var width = img.naturalWidth; // this will be 300 
    var height = img.naturalHeight; // this will be 400 
    someContext.drawImage(img, 0, 0, width, height); 
}, false); 

img.src = 'http://placekitten.com/300/400'; // grab a 300x400 image from placekitten 

Es una buena idea para configurar la fuente sólo después se define el detector de eventos, ver la exploración de Phrogz en ese aquí: Should setting an image src to data URL be available immediately?

+0

¿Admitirá todos los navegadores modernos? – LittleFunny

3

no puede recuperar anchura/altura ante la imagen ha sido cargado.

Pruebe algo como:

// create new Image or get it right from DOM, 
// var img = document.getElementById("myImage"); 
var img = new Image(); 

img.onload = function() { 
    // this.width contains image width 
    // this.height contains image height 
} 

img.src = "image.png"; 

De todos modos onload no se disparará si la imagen se ha cargado antes de la ejecución del script. Finalmente, puede insertar una secuencia de comandos en html <img src="test.jpg" onload="something()">

Cuestiones relacionadas