2012-02-03 72 views
5

在图像标签中,如果我们不提供宽度和高度属性,那么当检索图像的宽度和高度时,我们什么也得不到。我使用canvas元素来加载图像并按比例缩放它。为了做到这一点,我必须得到实际的图像大小。有没有可能在HTML 5中做到这一点?我们可以通过画布获得真实的图像大小吗?

回答

0

不完全明白你的问题。

但是,您可以使用JavaScript来获取图像的宽度和高度。

,然后将其传递到

/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); 

而在画布上绘制图像。

或查看它是否有助于

http://jsfiddle.net/jjUHs/

1

如果我理解正确的话,你可以使用getComputedStyle方法。

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

HTMLImageElement具有用于这两个属性,naturalWidthnaturalHeight。使用这些。

如:

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 

这是明智的设置事件监听器被定义后,才源,看到这里Phrogz的探索:Should setting an image src to data URL be available immediately?

+0

它会支持所有现代浏览器 – LittleFunny 2012-02-04 11:16:32

3

无法检索宽度/高度形象一直前加载。

试着这么做:

// 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"; 

总之,如果形象脚本执行之前被加载的onload不会火。最终你可以在html中嵌入脚本<img src="test.jpg" onload="something()">

相关问题