I have an image on my page which I can fetch via $('#myimage'); Now I want to find the coordinates of square which I will draw on image. These end points of square should be exactly such that radius of square should be 开发者_开发百科20px(the center of the square will be center of image). How can I get do the same with JavaScript or jQuery.
var dims = {x: 20, y: 20},
obj = $('#myImage'),
img = obj.offset(),
coords = {top: img.top + (obj.height()-dims.y)/2,
left: img.left + (obj.width()-dims.x)/2};
Working example: http://jsfiddle.net/22TMD/
You can use position()
instead of offset()
if you want it relative to the offset parent and not the document (depends on how you're going to add the square in the markup). So too, you can use innerHeight()
and outerHeight()
depending on the styling of the image.
精彩评论