开发者

weird positioning problem while rotating image in Javascript

I am running into a weird positioning issue while rotating an image wrapped into a div in JavaScript. When rotating the image by either 90 or 270 degrees, the image suddenly is 50px above and 50px to the right of its parent div. For 0 or 180 degrees it's just fine.

This is what I am doing:

<html>
<head>
    <script type="text/javascript" language="javascript" src="http:开发者_开发知识库//code.jquery.com/jquery-1.6.2.js"></script>
</head>
<body>
    <div id="crop_container" style="width:400px; height:400px; border:solid 1px;">
        <img src="http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc6/249740_10150195623627623_506197622_7383520_7286937_n.jpg" style="display:block; position:relative; width:400px; height:400px;" />
    </div>
    <script language="JavaScript">
    var $cropContainer =  $("#crop_container");
    var $cropImage =  $("#crop_container img");
    var degrees = 90;

    $cropImage.css({"width":400, "height":300});
    $cropContainer.css({"width":300, "height":400});
    $cropImage.css({"-webkit-transform":"rotate("+degrees+"deg)","-moz-transform":"rotate("+degrees+"deg)"});
    //$cropImage.css({"top":50, "right":50});
    </script>
</body>
</html>

Now when you uncommect the last css adjustment line with a correction of 50px from top and right it works just fine, but I have no clue as to why this is happening?

Any advice would be greatly appreciated!

Thanks! Joni


It depends on what you expect it to do. It is rotating around the midpoint of the image, not the rectangle.

  • Midpoint placeholder: (150, 200)
  • Midpoint image: (200, 150).

Indeed, there is a 50px difference. You could change the midpoint of rotating before rotating by translating:

translate(-50px, 50px) rotate("+degrees+"deg)

so that the image midpoint becomes (200 - 50, 150 + 50) which is (150, 200), what you want.

http://jsfiddle.net/4UUJN/2/


When you rotate a landscape image by 90 degrees into a portrait image it will keep it centered to it's original position. Since your width and height are 100 pixels apart from one another, the transform distributes the difference to the top and bottom, that's where your 50 pixels comes from.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜