首页 > 解决方案 > 根据高度计算圆上的位置(X,Y)

问题描述

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

图片你有这个代码:

#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%;' />";
}

所以,现在一个x2and的例子y2看起来像这样:

基本上,我们知道top圆 ( off_nadrz.top)、bottom圆 ( off_nadrz.top + (off_nadrz.height / 2)) 和height圆 ( ) 的坐标off_nadrz.height。我们也知道 psuedo_element (圆圈中的蓝色事物)的相同事物。由此我们需要计算x2y2

感谢您的每一个建议,因为我现在正在与这个问题作斗争 2 天......

标签: javascriptmath

解决方案


你只需要应用圆周公式:

    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 ) );

推荐阅读