Matthieu Marcé
Matthieu Marcé

Reputation: 172

How to define a circular area to set random coordinates in a PHP generated picture?

I'm trying to draw circles at random positions in a PHP generated picture, starting from the center point of image and contained in a "N" pixels radius.

I know how to do it in square boundaries (and i would quite know how to do it in a diamond shape too), but the circular way to do it is a bit more difficult to comprehend for me.

Here is the code i've got so far. The image is 600*600px, i generate 100 white circles of 25*25px in a 300*300px square area horizontally and vertically centered.

$w = $h = 600;
$img = imagecreatetruecolor($w,$h);
$cl = imagecolorallocatealpha($img,255,255,255,0);
for ($i=0;$i<=100;$i++){ // GENERATE 100 CIRCLES
    $x = rand(150,450);
    $y = rand(150,450);
    imagefilledellipse($img, $x, $y, 25, 25, $cl);
}
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);

What would be the best way to generate these circles in circular boundaries ?

So that, for instance, if $x=155 it could not be at $y=155, or if $x=445 it could not be $y=445

Thanks for help !

EDIT This is the new code with polar coordinates

$w = $h = 600;
$img = imagecreatetruecolor($w,$h);
$cl = imagecolorallocatealpha($img,255,255,255,0);
for ($i=0;$i<=100;$i++){ // GENERATE 100 CIRCLES
    $r = rand(25,(300-25));
    $a = rand(0,360);
    $x = $r * cos(deg2rad($a));
    $y = $r * sin(deg2rad($a));
    imagefilledellipse($img, $x, $y, 25, 25, $cl);
}
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);

Upvotes: 1

Views: 237

Answers (1)

Joffrey Schmitz
Joffrey Schmitz

Reputation: 2438

Instead of trying to find the (x,y) coordinates, you can randomize the polar coordinates:

  • angle between 0° and 360°
  • radius between 25 and 300-25 : with these limits, you are sure that your small circles will always be inside the circle boundary.

And then convert these polar coordinates via the standard formulas

x = r * cos(t)
y = r * sin(t)

Upvotes: 1

Related Questions