Engo Engo - 8 months ago 45
Javascript Question

How to generate new random circles based on distance from head circle in JavaScript?

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?

enter image description here


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.arc(x, y, r, 0, 2 * Math.PI, false)
context.fillStyle = "#fc3358"


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));