【发布时间】:2012-02-26 02:14:11
【问题描述】:
在图像标签中,如果我们不提供宽度和高度属性,则在检索图像的宽度和高度时将一无所获。我正在使用画布元素加载图像并按比例缩放。为了做到这一点,我必须得到实际的图像大小。是否可以在 html 5 中做到这一点?
【问题讨论】:
在图像标签中,如果我们不提供宽度和高度属性,则在检索图像的宽度和高度时将一无所获。我正在使用画布元素加载图像并按比例缩放。为了做到这一点,我必须得到实际的图像大小。是否可以在 html 5 中做到这一点?
【问题讨论】:
HTMLImageElement 有两个属性,naturalWidth 和 naturalHeight。使用那些。
如:
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?
【讨论】:
您无法在图像加载之前检索宽度/高度。
尝试类似:
// 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()">
【讨论】:
如果我理解正确,您可以使用getComputedStyle 方法。
var object = document.getElementById(el);
var computedHeight = document.defaultView.getComputedStyle(object, "").getPropertyValue("width");
【讨论】:
没有完全理解你的问题。
但是你可以使用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);
在画布上绘制图像时。
如果有帮助,请检查一下
【讨论】: