[英]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)
如果您不想将原点作为中心,则可以使用完整公式来获取x
是Math.sqrt( Math.pow(radius, 2) - Math.pow((actualY - centerY), 2) , 2)
说明:
原始方程(xa)² + (y'-b)² = r²
变为x = √(r² - (y'-b)²) + a
假设
.rotating
盒的宽度和高度为0。
代码中的等效变量为centerX
= a
, centerY
= 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.