Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use X,Y coordinates to plot points inside a circle

Is there a way in javascript to plot x,y coordinates so they fall into a circle rather than a square?

For example if I have the following code:

  circleRadius = 100;
  context.drawImage(img_elem, dx, dy, dw, dh);

I need to figure out a combination of x,y values that would fall inside a 100 pixel circle.

Thanks!

like image 744
Rigil Avatar asked Jan 16 '11 20:01

Rigil


1 Answers

  1. choose an x at random between -100 and 100
  2. a circle is defined by x^2 + y^2 = r^2, which in your case equals 100^2 = 10000
  3. From this equation you can get that y^2 = 10000 - x^2 , therefore the points with a chosen x and y = +/-sqrt(10000 - x^2) will lye on the circle.
  4. choose an y at random between the two coordinates found at point 3
  5. You're set!

EDIT: In JS:

var radius = 100;
x = Math.random() * 2 * radius - radius;
ylim = Math.sqrt(radius * radius - x * x);
y = Math.random() * 2 * ylim - ylim;

Another edit: a jsFiddle Example

like image 61
nico Avatar answered Sep 20 '22 02:09

nico