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>
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.