【问题标题】:Centering an image with absolute position (top, left)以绝对位置居中图像(上、左)
【发布时间】:2013-10-31 01:38:12
【问题描述】:

我正在使用参数方程来围绕一个圆圈定位图像 (How do I calculate a point on a circle’s circumference?)

我用简单的数学来做这件事:

// x,y position on circumference:
// x = a + r * cos(t)
// y = b + r * sin(t)

.position {
left: @a + ( @r *  cos(@t) );
top: @b + ( @r *  sin(@t) );
}

我遇到的麻烦是这会将图像定位在左上角,而不是图像的中心,因此没有考虑到高度和宽度的视觉偏移。尝试通过 height/2, width/2 调整不起作用,因为每个图像的角度不同。

有没有一种简单的方法可以以这种方式定位图像,使其以 x,y 为中心?

【问题讨论】:

  • 如果我误解了您在我的回答中想要做什么,请告诉我。我投了反对票(不知道为什么),所以我想确定我理解你的要求是正确的。我相信您正在尝试将图像围绕某个圆的圆周居中,并以该圆周围的某个角度参考定位。对吗?

标签: javascript jquery css less


【解决方案1】:
.position {
    left: @a + ( @r *  cos(@t) );
    top: @b + ( @r *  sin(@t) );

    margin-left: -@r;
    margin-top: -@r;
}

你可以这样做而不是计算:

top:50%;
left:50%; 
position:absolute; 

margin-left:-@r;
margin-top:-@r;

FIDDLE DEMO

【讨论】:

  • 谢谢,但这是不正确的。它只是在两个轴上添加一个与半径相等的边距。
  • @alias51 抱歉,应该是-@r
【解决方案2】:

减去半宽/高度确实有效

您说您尝试了半宽度/高度计算以尝试以某个角度参考将图像居中在圆的圆周上(据我了解您的问题)。似乎应该并且确实有效。看看这个...

Example Fiddle

圆圈和图像颜色仅供视觉参考,但图像定位由以下人员完成:

//define circle position
@r: 100px;
@x: 175px;
@y: 150px;
.setImage(@w, @h, @a) {
    //@a is angle from HORIZONTAL but moves clockwise 
    //(based on radians unless units are given)
    width: @w;
    height: @h;
    left: (@x + ( @r *  cos(@a) ) - (@w / 2));
    top: (@y + ( @r *  sin(@a) ) - (@h / 2));
}
.test1 {
  .setImage(40px, 40px, -35deg);
}
.test2 {
  .setImage(60px, 30px, -80deg);
}
.test3 {
  .setImage(90px, 20px, -150deg);
}
.test4 {
  .setImage(40px, 70px, -240deg);
}
.test5 {
  .setImage(20px, 90px, -295deg);
}

CSS 输出

.test1 {
  width: 40px;
  height: 40px;
  left: 236.9152044288992px;
  top: 72.64235636489539px;
}
.test2 {
  width: 60px;
  height: 30px;
  left: 162.36481776669305px;
  top: 36.5192246987792px;
}
.test3 {
  width: 90px;
  height: 20px;
  left: 43.39745962155612px;
  top: 90px;
}
.test4 {
  width: 40px;
  height: 70px;
  left: 104.99999999999996px;
  top: 201.60254037844385px;
}
.test5 {
  width: 20px;
  height: 90px;
  left: 207.26182617406997px;
  top: 195.630778703665px;
}

即使是旋转图像也可以使用

假设您将图像设置为transform-origin: center center,那么即使图像以某个角度旋转,也可以将它们保持在中心。

See Rotated Image Example Fiddle

【讨论】:

    猜你喜欢
    • 2016-08-25
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2012-03-28
    相关资源
    最近更新 更多