使用javascript围绕某个点旋转元素(不使用变换原点)



我希望能够在元素围绕某个点旋转后返回它的共字。这就是我目前所掌握的(但这是不正确的)。

function rotateAroundPoint(pointX,pointY,angle) {
    //converting degrees to rads
    angle = angle * Math.PI / 180.0
    newX = Math.cos(angle) * pointX - Math.sin(angle) * pointY;
    newY = Math.sin(angle) * pointX + Math.cos(angle) * pointY;
    return({x:newX,y:newY});
}
var result = rotate(50,50,45);
/* offsetting by the result should make it look rotated around the point 50 50 */        
document.getElementById("div").setAttribute("style","top:"+(result.y)+"px;left:"+(result.x)+"px;");

css:

 #div
{
width:100px;
height:100px;
padding:10px;
position: absolute;
border: 1px solid black;
background-color: red;
-webkit-transform: rotate(45deg);
}

CSS变换围绕元素的中心旋转;我知道您希望移动元素,使其看起来围绕不同的点旋转。自然的方法是转换原点,但你说你不想这样做——我认为你有充分的理由。

您需要做的是将元素的位置偏移其中心绕该点旋转时的移动量。因此:

  1. 设点p=元素宽度和高度的一半(如有必要,使用getComputedStyle
  2. p=p-旋转原点
  3. p=旋转p角度)(其中rotate是代码中的(误名,因为它不是绕点旋转,而是绕原点旋转)函数)
  4. p=p+旋转原点
  5. p=p-元素大小的一半

p现在包含要分配给左上角的值。请注意,步骤2–4是绕除原点以外的点旋转的正常过程;步骤1和5只是从默认变换原点向后偏移。


如果这是而不是,请提供一张图表,显示您想要的结果。