How to get x, y distance from a circle

大憨熊 提交于 2019-12-24 19:33:54

问题


I've drawn a square shape whose width & length 20x, or 20y then I have drawn a circle inside the square whose radius 10x. Now a ray from the center of the circle went through the boundary of the circle at 45-degree angle (it can be 38 degrees or anything). Now how can i get x & y distance of connection ground of ray & circle from the square shape?

I've tried this code:

var radius = 10 //radius,
    x = Math.cos(Math.PI * 45 / 180) * radius
    y = Math.sin(Math.PI * 45 / 180) * radius

I'm not getting the exact distance with this code, what is the currect way to get this x & y distance?


回答1:


It seems that your coord origin is the top left of the enclosing square and the y axis is oriented downwards.

In that case,

var radius = 10 //radius,
    x = radius + Math.cos(Math.PI * 45 / 180) * radius
    y = radius - Math.sin(Math.PI * 45 / 180) * radius



回答2:


[update] you can get the x & y distances using this formulas:

var radius = 10 //radius,

var angle = 90

var d = Math.PI/180 //to convert deg to rads

if (0 <= angle & angle <= 45){
    deg = angle * d
    x = radius * Math.cos(deg)
    y = radius * Math.sin(deg)
}else if( 45 < angle & angle <= 90){
    deg = (90-angle) * d
    x = radius * Math.sin(deg)
    y = radius * Math.cos(deg)
}

console.log("x = " + x)
console.log("y = " + y)

If the angle is less than 45° we use the normal formulas as shown in the code.

But if the angle is greater than 45° we have to use the angle between the line and the y-axis which equal to 90-(angle value).

I hope this will solve your problem.




回答3:


After someone's edit, your post contains the correct expressions for calculating x and y coordinates from the center of the circle ("from center" row in the table). In order to get the "remaining" part to the edges of its bounding square ("to border" row in the table), these distances can be subtracted from the radius:

function calculate(){
  var radius=document.getElementById("radius").valueAsNumber||10;
  var radians=document.getElementById("degrees").valueAsNumber*Math.PI/180||0;
  document.getElementById("x1").innerHTML=radius*Math.cos(radians);
  document.getElementById("y1").innerHTML=radius*Math.sin(radians);
  document.getElementById("x2").innerHTML=radius-radius*Math.cos(radians)
  document.getElementById("y2").innerHTML=radius-radius*Math.sin(radians)
}
<input type="number" placeholder="radius" id="radius"><br>
<input type="number" placeholder="degrees" id="degrees"><br>
<button onclick="calculate()">Calculate</button><br>
<table border="1">
<tr><th></th><th>x</th><th>y</th></tr>
<tr><th>from center</th><td id="x1"></td><td id="y1"></td></tr>
<tr><th>to border</th><td id="x2"></td><td id="y2"></td></tr>
</table>


来源:https://stackoverflow.com/questions/51484631/how-to-get-x-y-distance-from-a-circle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!