resized image coordinates in html
I have an image in a html page resized to 400px 开发者_运维百科width with css
.cropbox {
width: 400px;
height : auto;
}
Also i have a js on that image that let the user select one point of the image. Of course the coordinates are relative on the resized image. How can i get the coordinates relative on the original image?
Something like newx = originalwidth/400 * x
but how to get the originalwidth?
AFAIK you won't be able to get the physical dimension of the image using javascript only. You have to calculate that in server side.
how to get the originalwidth?
There's not a simple way operating on the in-page image. You'd have to create an img
for the unresized version of the image, add it to the page and measure its offsetWidth
. Maybe you could do that by having the image unresized on the page in the markup to begin with, then on body onload
(at which point all images have been loaded) measure the natural size of the image then apply the resizing from script.
As someone already suggested, you should let your image load w/o any width applied to it and record it. however, you don't need any server side scripting to do it, you can:
- Hide original image so it won't 'blink' or do anything funny with page layout before resize (this is probably optional)
- Let it load, and record its dimensions onload
- When load is ready, resize it
- Finally, you can get both dimensions
My code in jQuery will do it for you:
<img id="myImage" style="display:none;" src="http://www.google.com/intl/en_ALL/images/logo.gif" alt="Google!" />
<div id="status"></div>
<script type="text/javascript">
var ImageModifier = {
WIDTH: 400,
Original: null,
Init: function() {
$(function(){
$('#myImage').load(function(){
//remember original size
ImageModifier.Original = { width: $(this).width(), height: $(this).height()}
//Resize the image
$(this).css("width", ImageModifier.WIDTH);
//print info after resize
ImageModifier.Info(this);
//show the image
$(this).css("display", "block");
});
});
},
Info: function(obj){
$('#status').append("Original Size: [" + ImageModifier.Original.width + "x" + ImageModifier.Original.height +"]" +
"<br />Current size: [" + $(obj).width() + "x" + $(obj).height() +"]<br />");
}
}
ImageModifier.Init();
</script>
精彩评论