簡體   English   中英

在Javascript中找到圓與線的相交點

[英]Find the Points of Intersection of a Circle with a Line in Javascript

我正在嘗試給定元素設置動畫以使其繞預定半徑移動,而我無法在給定的Y點獲得該元素的位置。

我試圖用圓方程找到每個點,但是我只能從兩個可能的點中得到一個點。

圓方程 在Javascript中,我使用Math.sqrt( Math.pow(radius, 2) - Math.pow(y, 2) , 2)來說明問題。 假設圓的中心為0,0。 但隨后我需要將其轉換為屏幕上的像素,因為瀏覽器上的位置沒有負像素。

所有大小均與窗口有關。 因此半徑在我的測試中是窗口高度的80%。

另外,我正在嘗試計算元素在持續時間內每幀之間的距離,但是我尚未使用它,因為我先嘗試解決上述問題。

這是我所擁有的(清理版本):

let height = window.innerHeight * 0.8,
    radius = height / 2,
    circumferance = (radius * 2) * Math.PI,
    container = document.getElementById('container'),
    rotating = document.querySelector('.rotating'),
    centerX = radius - (rotating.offsetWidth / 2),
    centerY = radius - (rotating.offsetHeight / 2),
    duration = 10,
        stepDistance = circumferance / 16;

// Setting the dimensions of the container element.
container.style.height = height + 'px';
container.style.width = height + 'px';

// return positive X of any given Y.
function getXOffset(y) {
    return Math.sqrt( Math.pow(radius, 2) - Math.pow(y, 2) , 2);
}

// Setting the position of the rotating element to the start.
rotating.style.top = 0 + 'px';
rotating.style.left = centerX + 'px';

setInterval(() => {
  let top = parseInt(rotating.style.top),
        y = radius - top;

    rotating.style.top = (top + 1) + 'px';
    rotating.style.left = (centerX + getXOffset(y)) + 'px';
}, 16);

這是一個帶有更多代碼的小提琴,用於嘗試使點之間的距離保持適當的距離,以使動畫更流暢(當前需要修復,但這還不打擾我。) https://jsfiddle.net/shock/1qcfvr4y /

最后一點:我知道CSS可能還有其他方法,但是我選擇使用javascript進行學習。

Math.sqrt將僅返回正根。 您必須根據應用程序考慮負值。 在這種情況下,您需要在循環的前半部分輸入正x值,在后半部分輸入負值x 為此,您應該實現一種方法來跟蹤進度並相應地反轉符號。

這是一個樣本 我修改了你的。

編輯:

代替Math.sqrt( Math.pow(radius, 2) - Math.pow(y, 2) , 2)如果您不想將原點作為中心,則可以使用完整公式來獲取xMath.sqrt( Math.pow(radius, 2) - Math.pow((actualY - centerY), 2) , 2)

說明:

原始方程(xa)² + (y'-b)² = r²變為x = √(r² - (y'-b)²) + a

假設.rotating盒的寬度和高度為0。

代碼中的等效變量為centerX = acenterY = b 通過以原點為中心,基本上就是在進行預先計算,以便y值等於(y'-b) 因此, x = √(r² - y²) + a是有效的。

在初始狀態時, top = 0

(y'-b) => height - centerY 在您的代碼中y = radius => height/2 現在(height - centerY)等於(height/2)是圓被正方形容器限制的副作用,該正方形容器的高度決定y值。

換句話說,當您使用原點作為中心時,您要在圓方程之外獲取中心偏移並分別進行處理。 您可以通過使用整個公式來完成相同的操作,即x = √(r² - (y'-b)²) + a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM