Reputation: 177
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?
Upvotes: 0
Views: 2005
Reputation: 39
[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.cos(deg)
y = radius * Math.sin(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.
Upvotes: 2
Reputation: 13195
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>
Upvotes: 1
Reputation: 17238
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
Upvotes: 4