Specifications

Part 2 sets up some variables that we will use to actually draw the graph.
Working out the values for these sorts of variables can be tedious, but a bit of forethought
about what you want the finished image to look like will make the drawing process much eas-
ier. The values we use here were arrived at by sketching the desired effect on a piece of paper
and estimating the required proportions.
The $width variable is the total width of the canvas we will use. We also set up the left and
right margins (with $left_margin and $right_margin, respectively); the fatnessand spacing
between the bars ($bar_height and $bar_spacing); and the font, font sizes, and label position
($font, $title_size, $main_size, $small_size, and $text_indent).
Given these base values, we can then make a few calculations. We want to draw a baseline that
all the bars stretch out from. We can work out the position for this baseline by using the left
margin plus an allowance for the text labels for the X coordinate, and again an estimate from
our sketch for the Y coordinate.
We also work out two important values: first, the distance on the graph that represents one unit:
$bar_unit = ($width-($x+$right_margin)) / 100; // one “point” on the graph
This is the maximum length of the barsfrom the baseline to the right margindivided by
100 because our graph is going to show percentage values.
The second value is the total height that we need for the canvas:
$height = $num_candidates * ($bar_height + $bar_spacing) + 50;
This is basically the height per bar times the number of bars, plus an extra amount for the title.
Part 3 is shown in Listing 19.5.3.
LISTING 19.5.3 showpoll.phpPart 3 Sets Up the Graph, Ready for the Data to Be
Added
/*******************************************
Set up base image
*******************************************/
// create a blank canvas
$im = imagecreate($width,$height);
// Allocate colors
$white=ImageColorAllocate($im,255,255,255);
$blue=ImageColorAllocate($im,0,64,128);
$black=ImageColorAllocate($im,0,0,0);
$pink = ImageColorAllocate($im,255,78,243);
Advanced PHP Techniques
P
ART IV
424
24 7842 CH19 3/6/01 3:42 PM Page 424