phpalgorithmmath

How can you draw a circle point by point, moving sequentially along the circumference?


Please tell me how I can build a circle point by point, making sure to move sequentially around the circle like the hand of a clock.

Now I can build a circle, but in my loop the points are placed in a random order and at the end I get a circle.

theta = 0, x = 16, y = 6
theta = 1, x = 11, y = 14
theta = 2, x = 2, y = 15
theta = 3, x = -4, y = 7
theta = 4, x = -1, y = -2
theta = 5, x = 9, y = -4

I need to build a circle sequentially, so that for example I can draw only half a circle or draw a circle with certain changing colors. I assume it's all in radians, but we need to use degrees somehow. But I have no more ideas. Thanks.

$radius = 10;
$centerX = 6;
$centerY = 6;

$theta = 0;

$white = imagecolorallocate($im, 0, 255, 0);

while ($theta <= 360) {
    $x = round($centerX + $radius * cos($theta));
    $y = round($centerY + $radius * sin($theta));
    $theta += 1;

    imagesetpixel($im, $x, $y, $white);
}

I tried to use the deg2rad() function to somehow use degrees, but my knowledge of mathematics is not enough.


Solution

  • I tried to use the deg2rad() function to somehow use degrees"

    You were close. Both cos() and sin() expect radians so that part should have been right. Alternatively, you can work directly in radians. Rather than looping from 0 to 360, loop from 0 to 2 * M_PI and make your increments smaller (e.g. M_PI / 100).

    Additionally:

    All together, with some polishing:

    $radius = 150;
    $step = M_PI / 100;
    $centerX = $centerY = $radius;
    
    $im = imagecreate(2 * $radius, 2 * $radius);
    $black = imagecolorallocate($im, 0, 0, 0);
    $white = imagecolorallocate($im, 255, 255, 255);
    
    for ($theta = 0; $theta < 2 * M_PI; $theta += $step) {
        $x = round($centerX + $radius * cos($theta));
        $y = round($centerY + $radius * sin($theta));
        imagesetpixel($im, $x, $y, $white);
    }
    
    imagepng($im, '/tmp/circle.png');
    

    Output:

    Rendered circl

    Degrees version:

    $radius = 150;
    $step = 1;
    $centerX = $centerY = $radius;
    
    $im = imagecreate(2 * $radius, 2 * $radius);
    $black = imagecolorallocate($im, 0, 0, 0);
    $white = imagecolorallocate($im, 255, 255, 255);
    
    for ($theta = 0; $theta < 360; $theta += $step) {
        $x = round($centerX + $radius * cos(deg2rad($theta)));
        $y = round($centerY + $radius * sin(deg2rad($theta)));
        imagesetpixel($im, $x, $y, $white);
    }
    
    imagepng($im, '/tmp/circle.png');