Contents Previous Next

11.3 Adding lines and rectangles to a canvas

A canvas also makes a good background for using standard graphic primitives, for example circles and lines. What you first have to remember is that you are (so far) working with absolute screen coordinates and secondly all drawing primitives are found in the Image Class accessible as a property of the Graph class. So for example to draw a line between coordinate (0,0) and (100,100) you would have to add the line

 $graph->img-> Line(0,0 ,100,100);

To your code. The following example shows some of the graphic primitives you have access to in the Image class

(File: canvasex02.php)
<?php
// $Id: canvasex02.php,v 1.1 2002/08/27 20:08:57 aditus Exp $
include  "../jpgraph.php";
include 
"../jpgraph_canvas.php";

// Setup a basic canvas we can work 
$g = new CanvasGraph( 400,200,'auto' );
$g->SetMargin( 5,11,6 ,11);
$g->SetShadow();
$g->SetMarginColor( "teal");

// We need to stroke the plotarea and margin before we add the
// text since we otherwise would overwrite the text.
$g->InitFrame();

// Add a black line
$g->img-> SetColor( 'black');
$g->img-> Line(0,0 ,100,100);

// .. and a circle (x,y,diameter)
$g->img-> Circle(100,100 ,50);

// .. and a filled circle (x,y,diameter)
$g->img-> SetColor('red');
$g->img-> FilledCircle( 200,100,50 );

// .. add a rectangle
$g->img-> SetColor( 'green');
$g->img-> FilledRectangle( 10,10,50 ,50);

// .. add a filled rounded rectangle
$g->img-> SetColor( 'green');
$g->img-> FilledRoundedRectangle( 300,30,350 ,80,10);
// .. with a darker border
$g->img-> SetColor( 'darkgreen');
$g->img-> RoundedRectangle( 300,30,350 ,80,10);

// Stroke the graph
$g->Stroke();

?>

Pleas note the way to access these routines through the img property of the Graph class. Please also keep in mind that the coordinates are absolute.



Figure 185: Example of graphic primitives [src] 


A note on GD For those of you using GD 1.xx you might notice that the large "filled circle" isn't completely filled. This is because in GD 1.xx there are no low level primitives to fill an ellipse or circle so JpGraph tries to make the best out of a bad situation and manually fake a filled circle. For interest of speed JpGraph does not contain a complete (for example) Bresenham-circle fill but cheats by using some existing GD routines. This is not a perfect solution and for large filled circles like this you get some moire-patterns in the circle. If you upgrade to GD 2.x JpGraph will be able to make full use of those new existing methods and the fill will be perfect.


We refer you to the class reference to find out what other graphic primitives are available for use.


Contents Previous Next