Canvas
One of the more extensive and widely used widgets in Perl/Tk
is the canvas widget, which is used for drawing items such as
circles, squares, etc. The basic syntax for creating a canvas is
my $canvas = $mw->Canvas( [ option => value ]);
or, for a canvas with scrollbars,
my $canvas = $mw->Scrolled('Canvas', [ option => value ]);
We will explore the canvas widget more in later chapters
on the TkSheet application; here we just list the basic options.
Two of the more common options used are
- -width => amount: specifies the width in pixels of the canvas
- -height => amount: specifies the height in pixels of the canvas
The coordinate system used to specify points on the canvas is oriented
so that the x coordinate increases to the right and the y coordinate
increases downwards, with the origin being at the top left-hand corner.
There are a number of items available to place on the canvas - these
are listed below.
- $canvas->createArc(x1, y1, x2, y2): draws an arc within
the bounding rectangle specified by (x1, y1) and (x2, y2)
- $canvas->createBitmap(x, y, -bitmap => bitmap): places
a bitmap at the specified (x, y) location
- $canvas->createImage(x, y, -image => image): places an
image at the specified (x, y) location
- $canvas->createLine(x1, y1, x2, y2, [x3, y3, ...]): draws
a line from (x1, y1) to (x2, y2), and continues if additional
coordinates are specified
- $canvas->createOval(x1, y1, x2, y2): draws an oval
within the rectangle specified by (x1, y1) and (x2, y2)
- $canvas->createRectangle(x1, y1, x2, y2): draws a
rectangle specified by (x1, y1) and (x2, y2)
- $canvas->createPolygon(x1, y1, x2, y2, x3, y3, [x4, y4,...]):
draws a polygon connecting the given coordinates
- $canvas->createText(x, y, -text => 'text'): places the
specified text at (x, y)
The specification of bitmaps and images in the canvas follows that
as used for buttons discussed earlier.
An illustration of the canvas widget appears below,
#!perl
# file canvas.pl
use Tk;
use strict;
use warnings;
my $mw = MainWindow->new;
$mw->title('Canvas Example');
my $canvas = $mw->Scrolled('Canvas', -width => 200, -height => 300);
my $dino = $mw->Photo(-file => 'dino.gif');
my $arc = $canvas->createArc(40, 40, 80, 100);
my $bm = $canvas->createBitmap(30, 30, -bitmap => 'questhead');
my $img = $canvas->createImage(60, 220, -image => $dino);
my $line = $canvas->createLine(120, 120, 150, 180);
my $oval = $canvas->createOval(30, 80, 100, 150);
my $rec = $canvas->createRectangle(150, 200, 180, 290);
my $pol = $canvas->createPolygon(150, 20, 190, 60, 190, 120);
my $text = $canvas->createText(100, 290,
-text => 'Canvas example');
my $exit = $mw->Button(-text => 'Exit',
-command => [$mw => 'destroy']);
$canvas->pack;
$exit->pack;
MainLoop;
a screen shot of which appears below.
Figure 3.29:
Example of a canvas widget
|
Randy Kobes
2003-11-17