使用javascript围绕某个点旋转元素(不使用transform-origin)
我希望能够在围绕某个点旋转元素后返回元素的坐标。这是我到目前为止所拥有的(但这是不正确的)。
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);
}
I want to be able to return a co-ord of an element after it has been rotated around a certain point. This is what I have so far (but it is incorrect).
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;");
the css:
#div
{
width:100px;
height:100px;
padding:10px;
position: absolute;
border: 1px solid black;
background-color: red;
-webkit-transform: rotate(45deg);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CSS 变换围绕元素的中心旋转;我知道您希望移动元素,使其看起来围绕不同的点旋转。做到这一点的自然方法是变换起源,但你说你不想这样做——我假设你有一个很好的理由。
您需要做的是将元素的位置偏移其中心围绕该点旋转时移动的量。因此:
getCompulatedStyle
)。旋转
是(错误命名的) ,因为它不绕点旋转,而是绕原点旋转)代码中的函数)。p 现在包含分配给顶部/左侧的值。请注意,步骤 2-4 是绕原点以外的点旋转的正常过程;步骤 1 和 5 只是从默认变换原点偏移并返回。
如果这不是您想要的,那么请提供一个图表来显示您想要的结果。
The CSS transform rotates around the center of the element; I understand you are looking to move the element such that it appears to be rotated around a different point. The natural way to do it would be transform-origin, but you say you don't want to do that — I'll assume you have a good reason.
What you need to do is offset the position of the element by the amount its center would move if rotated about that point. Therefore:
getComputedStyle
, if necessary).rotate
is the (misnamed, as it does not rotate about a point but the origin) function in your code).p now contains the values to assign to top/left. Note that steps 2–4 are the normal procedure for rotating about a point other than the origin; steps 1 and 5 are simply offsetting from the default transform origin and back.
If this is not what you are looking for, then please provide a diagram showing the results you want.