绝对定位圆周围的元素

时间:2014-10-17 17:26:18

标签: javascript css geometry sin cos

我有一些带有嵌入式SVG的html,如下所示

<section id="deck-head">

    <svg xmlns="http://www.w3.org/2000/svg" width="250" height="250">

        <g>
            <title>Marker</title>
            <g id="marker-frame">
                <path fill="white" d="m133.300003,64.800003l0,-33.500004l-16.100006,0l0,33.299999c-30.799995,3.700005 -53.499996,29.599998 -53.499996,60.800003c0,33.900002 27.600002,61.299995 61.299999,61.299995s61.300003,-27.399994 61.300003,-61.299995c0,-30.900002 -23.600006,-56.599998 -53,-60.599998zm-53.5,60.699997c0,-24.900002 20.299995,-45.199997 45.199997,-45.199997s45.199997,20.299995 45.199997,45.199997s-20.199997,45.300003 -45.199997,45.300003s-45.199997,-20.400009 -45.199997,-45.300003z"/>
            </g>
        </g>

    </svg>

    <mark>90&deg;</mark>

</section>

我需要能够在不使用任何外部JavaScript库的情况下复制以下布局

Desired Layout

忽略红色

我已经成功地旋转了SVG,足以面向正确的方向 - 但是我遇到的麻烦是将元素置于粉红色圆圈的刻度/尖端的绝对位置,具体取决于旋转到的位置。

我所追随的逻辑在于: 获取圆心点 获得轮换 找出剩下的&amp;最高职位将基于上述情况。

然而,我完全迷失了计算将使得顶部和左侧坐标能够将标记绝对定位在应该位置的位置。

1 个答案:

答案 0 :(得分:1)

这些只是简单的极坐标。不需要jQuery,只是为了更容易操作。

&#13;
&#13;
var angle = 0, center = 125, radius = 110, pi = Math.PI;
setInterval(function(){
 angle += 1;
 $('#c').attr('transform', 'rotate(' + angle + ', 125, 125)');
 // calculate new coordinates for mark
 var x = center + radius * Math.cos(angle * pi / 180 - pi / 2);
 var y = center + radius * Math.sin(angle * pi / 180 - pi / 2);
 $('#m').css({top: y + 'px', left: x + 'px'});
}, 100);
&#13;
body {background-color:black;}
#m {position:absolute;}
section {poisition:relative;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<section id="deck-head">

    <svg xmlns="http://www.w3.org/2000/svg" width="250" height="250">

        <g>
            <title>Marker</title>
            <g id="marker-frame">
                <path fill="white" id="c" d="m133.300003,64.800003l0,-33.500004l-16.100006,0l0,33.299999c-30.799995,3.700005 -53.499996,29.599998 -53.499996,60.800003c0,33.900002 27.600002,61.299995 61.299999,61.299995s61.300003,-27.399994 61.300003,-61.299995c0,-30.900002 -23.600006,-56.599998 -53,-60.599998zm-53.5,60.699997c0,-24.900002 20.299995,-45.199997 45.199997,-45.199997s45.199997,20.299995 45.199997,45.199997s-20.199997,45.300003 -45.199997,45.300003s-45.199997,-20.400009 -45.199997,-45.300003z"/>
            </g>
        </g>

    </svg>

    <mark id='m'>90&deg;</mark>

</section>
&#13;
&#13;
&#13;