Perl Cairo tutorial - Draw many circles in random colours

This is one page of a Perl Cairo tutorial.

This shows drawing many circles in random colours. It also demonstrates circular paths being filled using fill.
#!/usr/bin/perl
use warnings;
use strict;
use Cairo;
# Get pi
use Math::Trig;
my $size = 500;
my $surface = Cairo::ImageSurface->create ('argb32', $size, $size);
my $cr = Cairo::Context->create ($surface);
$cr->rectangle (0, 0, $size, $size);
$cr->set_source_rgb (1, 1, 1);
$cr->fill ();
my $n_circles = 5;
my $space = $size / $n_circles;
my $offset = $space / 2;
my $radius = $space / 3; 
for my $i (0..$n_circles * $n_circles - 1) {
    my $x = $i % $n_circles;
    my $y = int ($i / $n_circles);
    $x = $x * $space + $offset;
    $y = $y * $space + $offset;
    $cr->set_source_rgb (rand (), rand (), rand ());
    $cr->arc ($x, $y, $radius, 0, 2 * pi);
    $cr->fill ();
}
$surface->write_to_png ('many-circles.png');

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer