Reputation: 969
I have drawn a circle on a random position within a range on a canvas in JavaScript.
I want to generate 2 more circles on a random position on a specific distance (200) from the center of the 1st circle.
There is a way to generate new coordinates until the distance is equal to 200, but there should be a better solution, right?
How can I do the following?
Code:
var x = getRandomInt(200, 800)
var y = getRandomInt(200, 400)
var r = 60
drawCircle (x, y, r)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
function drawCircle(x, y, r) {
context.beginPath()
context.arc(x, y, r, 0, 2 * Math.PI, false)
context.fillStyle = "#fc3358"
context.fill()
context.closePath()
}
Upvotes: 0
Views: 725
Reputation: 81
You can use pythagorean theorem to find out all points that are 200 distance from an other. You are basically looking for a circle that has a radius of 200. So in the end you will get a function, you plug that puppy in and assign it the random value. Have a look at the distance formula, it might clear the concept up.
Upvotes: 0
Reputation: 80167
To generate point at random angle with distance R (here 200) from central point (CX, CY), use simple trigonometry formula:
Phi = Random * 2 * Math.PI; //Random in range 0..1
X = CX + Round(R * Cos(Phi));
Y = CY + Round(R * Sin(Phi));
Upvotes: 2
Reputation: 169
You can use Pythagorean theorem as noted by Gabriel above. If you do not want to calculate all points, you can assign one set of numbers to be random, then you can manipulate the theorm to calculate the second number: b = Sqrt(c^2 - a^2)
Upvotes: 0