调整JavaScript大小后获取图像大小 [英] Get image size after resize JavaScript
问题描述
我正在尝试根据max-width / max-height数组调整图像大小。以下是我到目前为止所提出的内容:
I am trying to resize an image based off of a max-width/max-height array. Here's what I've come up with so far:
<html>
<head>
<title>Image resize test</title>
<script>
function createImage(){
//The max-width/max-height
var maxDim = [500,500];
//Create the image
var img = document.createElement("img");
img.setAttribute("src","http://nyrixcorp.com/images/eggplant_service.png");
document.body.appendChild(img);
//Function for resizing an image
function resize(){
//resize the image
var portrait = this.width < this.height;
this[portrait ? "height" : "width"] = maxDim[portrait ? 1 : 0];
//What is the height? PROBLEM HERE!!!
console.log(this.height);
}
//Is the image loaded already?
var temp = new Image();
temp.src = img.src;
var loaded = typeof temp.complete != "undefined" ? temp.complete : !isNaN(temp.width+temp.height) && temp.width+temp.height != 0;
//Fire the resize function
if (loaded) resize.call(img);
else img.addEventListener("load",resize,false);
}
</script>
</head>
<body onload="createImage()">
</body>
</html>
您应该可以按原样运行此文件。加载图像后,它可以获得宽度/高度。但是一旦你改变宽度,它仍然记录旧的高度。唯一正常工作的浏览器似乎是Firefox(较新版本)。在窗口加载完成之前,所有其他浏览器都不会更新height属性。
You should be able to run this file as-is. It is able to get the width/height after loading the image. But once you alter the width, it still logs the old height. The only browser that works correctly appears to be Firefox (newer versions). All the other browsers don't update the height attribute until the window is finished loading.
有没有人知道修复此问题?图片已经加载,但没有给出正确的尺寸调整尺寸。
Does anyone know a fix for this? The image is already loaded, but it isn't giving the correct resized dimensions.
推荐答案
您没有更改 height
但是,因为你的图像的高度>宽度,make portrait = false
;
You didn't change the height
yet, because your image's height > width, make portrait = false
;
当您更改宽度时,在IE8中,它只会调整宽度,但在chrome中它会改变宽度和高度,我认为这是浏览器所依赖的。
When you change the width, in IE8, it will only resize the width, but in chrome it will both change the width and height, I think this is browser depended.
你可以通过改变高度和手动来解决这个问题。
You can fix this by both change the height and with manually.
这篇关于调整JavaScript大小后获取图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!