根据高度计算圆上的位置(X,Y)

时间:2020-11-01 07:17:17

标签: javascript math

我认为标题有点混乱,所以我会说得更好。

具有此代码的图片:

#NadrzFrontView:before {
    --beginHeight: var(--startHeight);
    --endHeight: var(--finishHeight);
    animation: 2s fillin ease forwards;
    content: "";
    position: absolute;
    bottom: 0;
    width: 300px;
    height: 0;
    background-color: #00FFF5;
    display: inline-block;
}

#NadrzFrontView {
    width: 300px;
    height: 300px;
    border-radius: 50%;
    border: 3px solid black;
    position: relative;
    overflow: hidden;
}

<div id="NadrzFrontView" style="--startHeight: 0%; --finishHeight: 50%;"> </div>

它看起来像这样:

现在,您可以使用此脚本来检测元素的left, top positionheight

function getOffset(el) {
    var rect = el.getBoundingClientRect();
    return {
        left: rect.left + window.pageXOffset,
        top: rect.top + window.pageYOffset,
        width: rect.width || el.offsetWidth,
        height: rect.height || el.offsetHeight
    };
}

好吧,当我们能够找到这些时,我们开始解决问题:

function SomeFunction() {
    var thickness = 1;
    var color = '#000000';

    var off_nadrz = getOffset(document.getElementById('NadrzFrontView'));
    var elem = document.getElementById('NadrzFrontView');
    var pseudoStyle = window.getComputedStyle(elem, ':before');
    var off_pseudo_elem = getOffset(elem);
    off_pseudo_elem.top += parseInt(pseudoStyle.top, 10);
    off_pseudo_elem.left += parseInt(pseudoStyle.left, 10);
    off_pseudo_elem.height = parseInt(pseudoStyle.height, 10);

    //finding middle of the circle
    var x1 = off_nadrz.left + (off_nadrz.width / 2);
    var y1 = off_nadrz.top + (off_nadrz.height / 2);
    //draw point in the middle of circle
    document.getElementById("AllLines").innerHTML += CreateHtmlPoint(color, x1, y1);

    //fincding point on the side of an element
    var x2; //I need to find this -- see more in examples
    var y2; //I need to find this -- see more in examples
    document.getElementById("AllLines").innerHTML += CreateHtmlPoint(color, x2, y2); //This does not work
}
function CreateHtmlPoint(color, cx, cy) {
    cx -= 5; // - 5, because width of point is 10
    cy -= 5; // - 5, because height of point is 10
    return "<div style='padding:0px; z-index: 2; margin:0px; height: 10px; width: 10px; background-color:" + color + "; line-height:1px; position:absolute; left:" + cx + "px; top:" + cy + "px; border-radius: 50%;' />";
}

因此,现在x2y2的示例如下所示:

基本上,我们知道圆(top的{​​{1}},圆(off_nadrz.top的{​​{1}}和圆({{1} bottom)。我们还知道psuedo_element的相同内容(圆圈中的蓝色内容)。因此,我们需要计算off_nadrz.top + (off_nadrz.height / 2)height

感谢每个建议,因为我现在已经解决了2天了...

1 个答案:

答案 0 :(得分:1)

您只需应用周长公式:

    var y2 = y1 - ( off_pseudo_elem.height - off_nadrz.height / 2 );

一旦有y2,就计算x2:

    var r = off_nadrz.height / 2; // if the figure is a circle, not an ellipse
    var x2 = x1 + Math.sqrt( r * r - ( y2 - y1 ) * ( y2 - y1 ) );