I'm writing a jQuery function where I'd like to access both the native size of an image, and the size specified for it on the page. I'd like to set a variable for each.
How is that done?
Modern browsers
When I wrote this answer back in 2009 the browser landscape was much different. Nowadays any reasonably modern browser supports Pim Jager's suggestion using img.naturalWidth and img.naturalHeight. Have a look at his answer.
Legacy answer compatible with super old browsers
// find the element
var img = $('#imageid');
/*
* create an offscreen image that isn't scaled
* but contains the same image.
* Because it's cached it should be instantly here.
*/
var theImage = new Image();
theImage.src = img.attr("src");
// you should check here if the image has finished loading
// this can be done with theImage.complete
alert("Width: " + theImage.width);
alert("Height: " + theImage.height);
This should work:
var img = $('#imageid')[0]; //same as document.getElementById('imageid');
var width = img.naturalWidth;
var height = img.naturalHeight;
The naturalWidth and naturalHeight return the size of the image response, not the display size.
According to Josh' comment this is not supported cross browser, this might be correct, I tested this in FF3
EDIT - new idea... see http://jsbin.com/uzoza
var fixedW = $("#imageToTest").width();
$("#imageToTest").removeAttr("width");
var realW = $("#imageToTest").width();
$("#imageToTest").attr("width", fixedW);
ORIGINAL ANSWER
see How to get image size (height & width) using JavaScript?
var img = $('#imageid');
var width = img.clientWidth;
var height = img.clientHeight;
I'm adding a way to accomplish this and be sure that there is support for all browsers. Pretty much all browsers support naturalWidth and naturalHeight except for Internet Explorer 8 and below.
Since IE 8 and below would return the size of the visible image and not the natural size when using trying to retrieve size values, a small workaround is needed to get the full size dimensions which came from an example by Jack Moore.
function naturalSize(imageid) {
imageid = (imageid.src ? imageid : document.getElementById(imageid));
if (document.documentMode < 9) {
var img = new Image();
img.src = imageid.src;
return {width: img.width,height: img.height};
}
return {width: imageid.naturalWidth,height: imageid.naturalHeight};
}
I set this up to support passing either the image ID value or the name of the ID.
Usage:
<img src="http://c64.exitof99.com/ims/VicGauntlet2013.png" id="some_img" width="400">
naturalSize("some_img");
// Returns: Object {width: 731, height: 387}
Or
<img src="http://c64.exitof99.com/ims/VicGauntlet2013.png"
onclick="aaa=naturalSize(this);alert('Size: '+aaa.width+'x'+aaa.height);">
// Displays: Size: 731x387
Be sure to make sure the image is loaded before calling this, whether by using onload or triggering upon adding it to the DOM.
Tested with:
Windows XP - Firefox 1.5, IE 8
Windows 7 - IE 9, Chrome 56
Android 6.0.1 - Chrome 50
Android 5.1.1 - Opera Mini 7.6, Dolphin 10.3
Full code example:
<!DOCTYPE html>
<html dir="LTR" lang="en"><head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body class="assignments" onload="run_test();">
<img src="http://c64.exitof99.com/ims/VicGauntlet2013.png" id="some_img" width="400">
<textarea id="outbox"></textarea>
<script type="text/javascript">
function naturalSize(imageid) {
imageid = (imageid.src ? imageid : document.getElementById(imageid));
if (document.documentMode < 9) {
var img = new Image();
img.src = imageid.src;
return {width: img.width,height: img.height};
}
return {width: imageid.naturalWidth,height: imageid.naturalHeight};
}
function run_test() {
var a = naturalSize("some_img");
document.getElementById("outbox").innerHTML = "Size: "+a.width+"x"+a.height;
}
</script>
</body></html>
My solution would be to write a web service that gets/downloads the image, and then gets its resolution and returns it as {width: x,height:y}. Then you call it with $.ajax or equivalent to retrieve this.
Alternatively you could add the image to a hidden div using
// e.g. don't set width and height
$("#hiddendiv").html("<img src='theurl'>");
And then get the div's width/height though I haven't tried it.
Related
It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the original element and animate the canvas.
Can it be done?
There is a library that try to do what you say.
See this examples and get the code
http://hertzen.com/experiments/jsfeedback/
http://html2canvas.hertzen.com/
Reads the DOM, from the html and render it to a canvas, fail on some, but in general works.
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Its key trick was:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
That is, it used a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details — basically it's a lot more limited than an iframe or AJAX due to privacy and cross-domain concerns.)
Sorry, the browser won't render HTML into a canvas.
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)
You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:
var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(img, 0, 0);
parent.removeChild(node);
parent.appendChild(canvas);
};
img.src = pngDataUrl;
});
And here is jsfiddle
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
No such thing, sorry.
Though the spec states:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
Which may be as close as you'll get.
A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.
The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
this code work with the library: https://github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
**the "canvas_out" is the id of the div that will contain the canvas
so try this code.
:
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work.
Comenten si les sirvio :)
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}
I'm using Raphael to draw an object, then transferring it to an HTML canvas element with canvg so that I can use toDataURL to save it as a PNG. But when I use canvg, the resulting image is blurry. The code below, for example, produces this (raphael on top, canvg on bottom):
<html>
<head>
<script src="lib/raphael-min.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script src="lib/raphael.export.js"></script>
</head>
<body>
<div id="raph_canvas"></div><br>
<canvas id="html_canvas" width="50px" height="50px"></canvas>
<script language="JavaScript">
var test=Raphael("raph_canvas",50,50);
var rect=test.rect(0,0,50,50);
rect.attr({fill: '#fff000', 'fill-opacity':1, 'stroke-width':1})
window.onload = function() {
var canvas_svg = test.toSVG();
canvg('html_canvas',canvas_svg);
var canvas_html = document.getElementById("html_canvas");
}
</script>
</body>
</html>
The blurriness is evident in the png created by toDataURL as well. Any idea what is going on here? I don't think this has anything to do with re-sizing. I've tried setting ignoreDimensions: True and some other things.
Another datapoint. If I use raphael to output some text and then use canvg, it is not only blurry but the wrong font!
And here is the test.rect(0.5,0.5,50,50) suggested. Still blurry:
So it took me a while, but then it dawned on me. All your example images are twice the size the code claims they should be. So you're most likely on some sort of HDPI device (Retina MacBook Pro ect...) SVG is great because its resolution independent, canvas on the other hand is not. The issue you're seeing has to do with how canvas renders. To fix this, you need to prep the canvas so that your drawing will be done at the resolution of your screen.
http://jsbin.com/liquxiyi/3/edit?html,js,output
This jsbin example should look great on any screen.
The trick:
var cv = document.getElementById('box');
var ctx = cv.getContext("2d");
// SVG is resolution independent. Canvas is not. We need to make our canvas
// High Resolution.
// lets get the resolution of our device.
var pixelRatio = window.devicePixelRatio || 1;
// lets scale the canvas and change its CSS width/height to make it high res.
cv.style.width = cv.width +'px';
cv.style.height = cv.height +'px';
cv.width *= pixelRatio;
cv.height *= pixelRatio;
// Now that its high res we need to compensate so our images can be drawn as
//normal, by scaling everything up by the pixelRatio.
ctx.setTransform(pixelRatio,0,0,pixelRatio,0,0);
// lets draw a box
// or in your case some parsed SVG
ctx.strokeRect(20.5,20.5,80,80);
// lets convert that into a dataURL
var ur = cv.toDataURL();
// result should look exactly like the canvas when using PNG (default)
var result = document.getElementById('result');
result.src=ur;
// we need our image to match the resolution of the canvas
result.style.width = cv.style.width;
result.style.height = cv.style.height;
This should explain the issue you're having, and hopefully point you in a good direction to fix it.
Another solution described in this article, similar to the one posted here, except it's using scale() and it's taking into account the pixel ratio of the backing store (browser underlying storage of the canvas):
var devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1,
ratio = devicePixelRatio / backingStoreRatio;
// upscale the canvas if the two ratios don't match
if(devicePixelRatio !== backingStoreRatio){
// adjust the original width and height of the canvas
canvas.width = originalWidth * ratio;
canvas.height = originalHeight * ratio;
// scale the context to reflect the changes above
context.scale(ratio, ratio);
}
// ...do the drawing here...
// use CSS to bring the entire thing back to the original size
canvas.style.width = originalWidth + 'px';
canvas.style.height = originalHeight + 'px';
I am trying to write a image magnifier with canvas, It works fine but the problem is when I mouseover the image the image drawn on the canvas is not positioned correctly based on the mouse position on the image.
You can see the problem here
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Magnifier</title>
<style type="text/css">
canvas
{
border:1px solid #000;
width:150px;
height:150px;
border-radius:80px;
position:absolute;
}
</style>
</head>
<body>
<img src="natural.jpg" height="400" id="image" width="600" onMouseMove="move(event);">
<canvas id="magnifier"></canvas>
<input type="button" name="magnify" id="magnify" value="magnify" onClick="magnify()" />
</body>
</html>
<script type="text/javascript">
var flag = 0;
var lens = document.getElementById('magnifier');
var img = document.getElementById('image');
var ctx=lens.getContext("2d");
function magnify()
{
flag = 1;
}
function move(e)
{
if(flag == 1)
{
var co_ord = getImageCoords(e,img);
var x = co_ord['x']+img.offsetLeft;
var y = co_ord['y']+img.offsetTop;
draw(x,y);
/*lens.style.top = y+"px";
lens.style.left = x+"px";*/
}
}
function getImageCoords(event,img) {
var cords = new Array;
cords['x'] = event.offsetX?(event.offsetX):event.pageX-img.offsetLeft;
cords['y'] = event.offsetY?(event.offsetY):event.pageY-img.offsetTop;
return cords;
}
function draw(a,b)
{
ctx.clearRect(0,0,lens.width,lens.height);
ctx.drawImage(img,a,b,150,150,0,0,300,150);
}
</script>
The main problem is that you are scaling the original image by forcing it into a 640 by 400 img element. The actual image is quite a bit larger. The width and height are just presentation settings, so when you draw the image ctx.drawImage(img,a,b,150,150,0,0,300,150); it is drawing the original unsized image. This means that your mouse coordinates do not match the location on the original image.
I can see two options:
1. Resize original by drawing to canvas
See update here. I haven't used cssdeck before, so here is a fiddle in case I didn't save it properly. Basically, it resizes the image to a canvas (resizeCanvas) and then uses this canvas for the drawing:
Relevant HTML:
<canvas id='resizeCanvas' height='400' width='600' onMouseMove="move(event);"></canvas>
Relevant JavaScript:
var ctxR=resizeCanvas.getContext("2d");
ctxR.drawImage(theImg,0,0,600,400);
There were a few other tweaks I made. First, you should specify the width and height attributes directly on the magnifier canvas. Otherwise, if this is different from the css then this will cause scaling. Then you can do the scaling to double the size by:
ctx.drawImage(img,a,b,150,150,0,0,300,300);
The only drawback of that approach is that you have a high res image that you are uploading and then losing some quality when you maginify which seems a pity. So, a better approach might be to load the original image without adding to the dom and then translate the x,y coords appropriately for the original image. Which is the second approach:
2. Scale x,y coordinates (better quality)
See the update here (fiddle here as well). As you can see, the quality is much better.
Here, we load the original image:
var origImage = document.createElement('img');
var origImage.src = '<image source>'
Then, just scale accordingly:
scaleX = origImage.width/img.width;
scaleY = origImage.height/img.height;
ctx.clearRect(0,0,lens.width,lens.height);
ctx.drawImage(img,a*scaleX,b*scaleY,150,150,0,0,150,150);
Note that we are not actually doing any resizing of the original image at all when we draw it to the canvas (width and height are 150 in all cases), instead we are just showing it at its larger native size. For smaller images, you may want to resize according to some fudge factor.
I have seen some similar questions here but not actually what I need to know!
I am using Flash CS6 and outputting a CreateJS framework animation instead of regular .swf files. When you publish from within the API (Flash) it generates an html5 doc and an external .js file with the actual javascript that defines the animation.
Here's what I need: I want my animation to either be able to go full screen and maintain it's aspect ratio -OR- be set at say 1024x768 and be centered in the browser window but if viewed on a mobile device, dynamically resize to fit the device screen size or viewport size and centered.
A perfect example of what I need is here: http://gopherwoodstudios.com/sandtrap/ but I don't see which code is doing the dynamic resizing in this example.
Any help would be greatly appreciated. In addition, I am supplying the html5/js output of the Flash API since it seems to be very, very different than the example code given in other canvas-related posts.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CreateJS export from index</title>
<script src="http://code.createjs.com/easeljs-0.5.0.min.js"></script>
<script src="http://code.createjs.com/tweenjs-0.3.0.min.js"></script>
<script src="http://code.createjs.com/movieclip-0.5.0.min.js"></script>
<script src="http://code.createjs.com/preloadjs-0.2.0.min.js"></script>
<script src="index.js"></script>
<script>
var canvas, stage, exportRoot;
function init() {
canvas = document.getElementById("canvas");
images = images||{};
var manifest = [
{src:"images/Mesh.png", id:"Mesh"},
{src:"images/Path_0.png", id:"Path_0"}
];
var loader = new createjs.PreloadJS(false);
loader.onFileLoad = handleFileLoad;
loader.onComplete = handleComplete;
loader.loadManifest(manifest);
}
function handleFileLoad(o) {
if (o.type == "image") { images[o.id] = o.result; }
}
function handleComplete() {
exportRoot = new lib.index();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
createjs.Ticker.setFPS(24);
createjs.Ticker.addListener(stage);
}
</script>
<style type="text/css">
body {text-align:center;}
#container { display:block;}
</style>
</head>
<body onload="init();" style="background-color:#D4D4D4">
<div id="container">
<canvas id="canvas" width="1024" height="768" style="background-color:#ffffff; margin: 20px auto 0px auto;"></canvas>
</div>
</body>
</html>
Thanks again!
don't know if you worked this one out in the end, but I recently had the same issue - I just needed to resize the whole createJs object to the viewport.
I added a listener to viewport resizing (I used jQuery), then resized the canvas stage to match the viewport, then using the height of the original flash stage height, or width depending on what you want (mine was 500), you can scale up the createJs movie object (exportRoot).
(function($){
$(window).resize(function(){
windowResize();
});
})(jQuery);
function windowResize(){
stage.canvas.width = window.innerWidth;
stage.canvas.height = window.innerHeight;
var test = (window.innerHeight/500)*1;
exportRoot.scaleX = exportRoot.scaleY = test;
}
Hope that helps someone!
function resizeGame()
{
widthToHeight = 600 / 350;
newWidth = window.innerWidth;
newHeight = window.innerHeight;
newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight)
{
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else
{
newHeight = newWidth / widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
}
scale = newWidthToHeight / widthToHeight;
stage.width = newWidth;
stage.height = newHeight;
gameArea.style.marginTop = ((window.innerHeight - newHeight) / 2) + 'px';
gameArea.style.marginLeft = ((window.innerWidth - newWidth) / 2) + 'px';
}
widthToHeight is your game canvas scaling ratio. gameArea is your div id
make it sure your html tag must contain
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
The inline width and the height of the canvas define "resolution" - setting a CSS style of width defines "scale". Think of it like canvas size and image size in photoshop.
Because width and height of elements isn't defined when you export, I'm struggling to come up with a good way to scale up. But, you can always scale down. Use CSS to set the max-width and max-height to be 1024x768 (or whatever your original is) and then set the regular width and height to be whatever you need (proportionately).
Then just use CSS to center - margin:auto and all that.
I find it useful to allow my canvas to be fluid based on width, and then adjust the height based on the aspect ratio on resize. There are a couple things to keep in mind.
You must assign a width & height attribute to the canvas element whether you're creating with javascript or with html
You have to adjust the object's style.height property, not the canvas height property directly.
If you follow this sort of example you can even use media queries to give even more flexibility. jsFiddle, if you please.
var el = document.getElementById('mycanvas');
var aspectRatio = el.height / el.width;
resizeCanv = function resize (){
var style = getComputedStyle(el);
var w = parseInt(style.width);
el.style.height = (w * this._aspectRatio) + 'px';
};
// TODO: add some logic to only apply to IE
window.addEventListener('resize', resizeCanv);
EDIT: I haven't tested this with any interactivity within the canvas, only layout and animations.
My user can upload really big images, and for cropping and display purposes i'm adding width attribute so it will fit well in the browser window. Real image size can be - say 1920 x 1080 px.
<!-- width added for display purpose -->
<img class="croppable" src="images/fhd.jpg" width="640" />
In order to calculate real selection box dimension (if the x coordinate is 20px then would be 60px in the original full hd picture) i need to get the full image size before apply the width attribute.
The problem is that this will return 640 as value, taking into account the width attribute:
// Important: Use load event to avoid problems with webkit browser like safari
// when using cached images
$(window).load(function(){
$('img.croppable').each(function(){
alert(this.width);
});
});
Please don't flag this as duplicate since what i'm asking is completly different from simple image width/height retrival (which works, actually).
EDIT: Chris G. solution seems not working:
$(window).load(function(){
$('img.croppable').each(function(){
console.log(this.src);
var original = new Image(this.src);
console.log(original);
$("#original_w").text(original.width); // Temp, more images to be added
$("#original_h").text(original.height); // Temp, more images to be added
});
});
Console output:
http://localhost/DigitLifeAdminExtension/images/pillars-of-creation.jpg
<img width="0">
Get the width/height of the image itself, not the div it is contained within.
$(window).load(function(){
$('img.croppable').each(function(){
var img = new Image();
img.src = $(this).src;
alert(img.width);
});
});
You can remove the attributes, get the width and put the attributes in place again:
var $img = $(img);
var oldWidth = $img.attr("width");
var imgWidth = $img.removeAttr("width").width();
$img.width(oldWidth);
But I think Chris G.'s answer works well too, just making sure it will be loaded when you try to get the width:
img.onload = function() {
if (!img.complete) return; // IMG not loaded
width = img.width;
imgManipulationGoesHere();
}
Works in most up-to-date browsers and IE9.
$(window).load(function(){
$('img.croppable').each(function(){
alert(this.naturalHeight);
});
});
The working solution would be:
$(function(){
$('img.croppable').each(function () {
var original = new Image(this.src);
original.onload = function () {
alert(original.src + ': ' + original.width + 'x' +original.height);
};
});
});