Index | Widgets |C API | Home Page

NAME
tkp::canvas - Create and manipulate path canvas widgets
SYNOPSIS
WIDGET-SPECIFIC OPTIONS
INTRODUCTION
WIDGET COMMAND
pathName ancestors tagOrId
pathName children tagOrId
pathName depth tagOrId
pathName distance tagOrId x y
pathName firstchild tagOrId
pathName gradient command ?options?
pathName gradient cget token option
pathName gradient configure token ?option? ?value option value...?
pathName gradient create ?name? type \fR?\fI-key value ...\fR?
pathName gradient delete token
pathName gradient inuse token
pathName gradient names
pathName gradient type token
pathName itempath ?options? tagOrId
-relative
-compact
pathName itemreconfigure tagOrId ?option value ...?
pathName lastchild tagOrId
pathName nextsibling tagOrId
pathName parent tagOrId
pathName prevsibling tagOrId
pathName style command ?options?
pathName style cget token option
pathName style configure token ?option? ?value option ...?
pathName style reconfigure token ?option value ...?
pathName style create ?name? ?option value ...?
pathName style delete token
pathName style inuse token
pathName style names
pathName types
NEW ITEMS
Circle Items
-r radius
Ellipse Items
-rx radius.
-ry radius.
Group Items
Path Items
M x y
L x y
H x
V y
A rx ry phi largeArc sweep x y
Q x1 y1 x y
T x y
C x1 y1 x2 y2 x y
S x2 y2 x y
Z
Pimage Items
-image image
-height size
-width size
Pline Items
Polyline Items
Ppolygon Items
Prect Items
-rx float
-ry float
Ptext Items
-text string
-anchor anchorPos
-font value
ITEM OPTIONS
Fill Options
-fill colorgrad
-fillopacity float
-fillrule value
Stroke Options
-stroke color
-strokedasharray dashArray
-strokelinecap value
-strokelinejoin value
-strokemiterlimit float
-strokeopacity float
-strokewidth float
Generic Options
-matrix value
-parent tagOrId
-state value
-style styleToken
-tags tagList
GRADIENT OPTIONS
-method value
-stops stopSpec ?stopSpec...?
-lineartransition value
-matrix value
-radialtransition value
-units value
MATRIX
Matrix Generation
tkp::transform rotate angle ?centerX centerY?
tkp::transform scale factorXY ?factorY?
tkp::transform skewx angle
tkp::transform skewy angle
tkp::transform translate x y
Matrix Inheritance
Matrix Details
{{sx 0} {0 sy} {0 0}}
{{1 0} {0 1} {tx ty}}
{{cos(a) sin(a)} {-sin(a) cos{a}} {0 0}}
SURFACES
tkp::surface new width height
tkp::surface names
Surface Token Commands
$token copy imageName
$token create type coords ?options?
$token destroy
$token erase x y width height
$token height
$token width
MISCELLANEOUS
Antialiasing
Pixelalign
Depixelize
VISIBLE DIFFERENCES
delete
lower/raise
find above/below
scale/move
tag all
KNOWN ISSUES
FURTHER DOCUMENTATION
COPYRIGHT

NAME

tkp::canvas - Create and manipulate path canvas widgets

SYNOPSIS

package require tkpath

tkp::canvas pathName ?options?

WIDGET-SPECIFIC OPTIONS

Options are the same as those accepted by the Tk canvas.

INTRODUCTION

The tkp::canvas command implements a canvas widget that adds the following new SVG item types:

path prect polyline ppolygon circle ellipse ptext group.

The canvas also provides a gradient facility for defining shaded fills, and an style abstraction. Canvas items are organized into a hierarchy under a single root item (id 0). This root item can not be deleted. The standard TK canvas items are all children of the root item. The new SVG items however, have a -parent option that can set to user created group items.

Note that facilities of tkp::canvas are all in addition to those of the original Tk canvas and is thus designed to be a drop-in replacement canvas. Also, tkpath provides support for multiple backends including: GDI (Windows), Quartz (MacOS) and Cairo (Unix et al).

WIDGET COMMAND

The tkp::canvas command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

where option and args determine the exact behavior of the command.

All of the standard Tk canvas commands are available in the tkpath canvas. In addition, the following extra commands are defined:

pathName ancestors tagOrId
Returns a list of item id's of the first item matching tagOrId starting with the root item with id 0.

pathName children tagOrId
Lists all children of the first item matching tagOrId.

pathName depth tagOrId
Returns the depth in the tree hierarchy of the first item matching tagOrId. The root item has depth 0 and children of the root has depth 1 and so on.

pathName distance tagOrId x y
Returns the closest distance between the point (x, y) and the first item matching tagOrId.

pathName firstchild tagOrId
Returns the first child item of the first item matching tagOrId. Applies only for groups.

pathName gradient command ?options?
Manage gradient fills used with -fill. Two types of gradients are available: linear and radial. See the GRADIENT OPTIONS section for a list of options accepted by gradients.

The following gradient commands are available:

pathName gradient cget token option
Returns the value of an option.

pathName gradient configure token ?option? ?value option value...?
Configures the object in the usual tcl way.

pathName gradient create ?name? type \fR?\fI-key value ...\fR?
Creates a gradient object of type linear or radial and returns its token.

pathName gradient delete token
Deletes the object.

pathName gradient inuse token
If any item is configured with the gradient token 1 is returned, else 0.

pathName gradient names
Returns all existing tokens.

pathName gradient type token
Returns the type of the gradient. linear or radial.

pathName itempath ?options? tagOrId
Return the SVG path for the given id. If an item is not representable as a path, the empty string is returned. The following options are available:

-relative
The returned path is to use lower case commands with relative coordinate.

-compact
The returned path uses comma separators between command arguments. Numbers ending in .0 are trimmed, and command atoms for line L are shortened to horizontal H or vertical V where possible.

pathName itemreconfigure tagOrId ?option value ...?
Does the same thing as itemconfigure, but in addition resets the modified flag back to false for each of the given options. This is used primarily on ids to reenable the group or style option to take precedence.

pathName lastchild tagOrId
Returns the last child item of the first item matching tagOrId. Applies only for groups.

pathName nextsibling tagOrId
Returns the next sibling item of the first item matching tagOrId. If tagOrId is the last child we return empty.

pathName parent tagOrId
Returns the parent item of the first item matching tagOrId. This command works for all items, also for the standard ones. It is therefore better to use this than 'cget id -parent' which is only supported for the new tkpath items.

pathName prevsibling tagOrId
Returns the previous sibling item of the first item matching tagOrId. If tagOrId is the first child we return empty.

pathName style command ?options?
Create/manage styles for use with -style. Styles provide an abstract way to specify common options. Generally options accepted by path item are also accepted by styles. Noteable exceptions include -style, -state, and -tags.

The style commands are as follows:

pathName style cget token option
Returns the value of an option.

pathName style configure token ?option? ?value option ...?
Configure the style. Takes any of the following options: -fill -fillopacity -fillrule -font -matrix -stroke -strokedasharray -strokelinecap -strokelinejoin -strokemiterlimit -strokeopacity -strokewidth.

pathName style reconfigure token ?option value ...?
Does the same thing as style configure, but in addition resets the modified flag back to false for each of the given options. This is used primarily on ids to reset the group or style option precedence.

pathName style create ?name? ?option value ...?
Creates a style object and returns its token. Accepts the same options as style configure\fI.

pathName style delete token
Deletes the object.

pathName style inuse token
If any item is configured with the style token 1 is returned, else 0.

pathName style names
Returns all existing tokens.

pathName types
List all item types defined in canvas.

NEW ITEMS

The create subcommand takes a number of new types:

circle, ellipse, group, path, pimage, pline, polyline, ppolygon, prect, ptext.

There are various differences with SVG. The display attribute names are adapted to tcl conventions, see below. Also, SVG is web oriented and therefore tolerates parameter errors to some degree, while tk is a programming tool and typically generates errors if parameters are wrong. Some syntax changes have also been made. One such is the -matrix option. Another is the SVG tag names which coincide with the ordinary canvas item names, but have added a "p" in front of its name instead.

Circle Items

A plain circle item: Circles are created with widget commands of the following form:

pathName create circle cx cy ?option value option value ...?

Options used may include generic, stroke, fill and the following item specific option:

-r radius
The circles radius; defaults to 0.0.

Ellipse Items

An ellipse item. Ellipses are created with widget commands of the following form:

pathName create ellipse cx cy ?option value option value ...?

Options used may include generic, stroke, fill and the following item specific option:

-rx radius.
The ellipse x-radius.

-ry radius.
The ellipse y-radius.

Group Items

Groups are created with widget commands of the following form:

pathName create group?option value option value ...?

Options used may include generic, stroke, and fill options.

A group item is merely a placeholder for other items, similar to how a frame widget is a container for other widgets. It is a building block for the tree structure. Unlike other items, and unlike frame widgets, it doesn't display anything. It has no coordinates which is an additional difference. The root item is a special group item with id 0 and tags equal to "root". The root group can be configured like other items, but its -tags and -parent options are read only. Options set in a group are inherited by its children but they never override options explicitly set in children. This also applies to group items configured with a -style.

Path Items

Paths accept an SVG path instead of coords. The general form is:

pathName create path pathSpec ?fillOptions strokeOptions genericOptions?

This path must be given as a single list item: it may not concateneted with the rest of the command. However, if comma separated options are used, whitespace can be ommited. For example:

pathName  create path {M 10 10 h 10 v 10 h -10 z} -fill blue
pathName  create path {M 10,10 h 10,v 10 h,-10 z} -fill blue
pathName  create path M10,10h10,v10h,-10z -fill blue

The input atoms supported are M L H V A Q T C, both upper and lower case (the lower case versions for relative coordinates). All path specifications are normalized on input to the fundamental atoms: M L A Q C. This means lower case (relative coordinate) atoms are converted to upper case (absolute coordinate) atoms. When you use the canvas coords command on a path item, the normalized path atoms is is returned. Note however that relative coordinates can be retrieved with .c itempath tag 1

Visualize this as a pen which always has a current coordinate after the first M. Coordinates are stored as floats:

M x y
Put the pen on the paper at specified coordinate. Must be the first atom but can appear any time later. The pen doesn't draw anything when moved to this point.

L x y
Draw a straight line to the given coordinate.

H x
Draw a horizontal line to the given x coordinate.

V y
Draw a vertical line to the given y coordinate.

A rx ry phi largeArc sweep x y
Draw an elliptical arc from the current point to (x, y). The points are on an ellipse with x-radius rx and y-radius ry. The ellipse is rotated by phi degrees. If the arc is less than 180 degrees, largeArc is zero, else it is one. If the arc is to be drawn in cw direction, sweep is one, and zero for the ccw direction.

NB: the start and end points may not coincide else the result is undefined. If you want to make a circle just do two 180 degree arcs.

Q x1 y1 x y
Draw a qadratic Bezier curve from the current point to (x, y) using control point (x1, y1).

T x y
Draw a qadratic Bezier curve from the current point to (x, y) The control point will be the reflection of the previous Q atoms control point. This makes smooth paths.

C x1 y1 x2 y2 x y
Draw a cubic Bezier curve from the current point to (x, y) using control points (x1, y1) and (x2, y2).

S x2 y2 x y
Draw a cubic Bezier curve from the current point to (x, y), using (x2, y2) as the control point for this new endpoint. The first control point will be the reflection of the previous C atoms ending control point. This makes smooth paths.

Z
Close path by drawing from the current point to the preceeding M point.

You may use lower case characters for all atoms which then means that all coordinates, where relevant, are interpreted as coordinates relative the current point.

Pimage Items

Displays an image in the canvas anchored at nw. If -width or -height is nonzero then the image is scaled to this size prior to any affine transform.

pathName create pimage x y  ?imageOptions genericOptions?

The image options include:

-image image
An image to draw.

-height size
Scale image to this height.

-width size
Scale image to this width.

Pline Items

Makes a single segment straight line. Ellipses are created with widget commands of the following form:

pathName create pline x1 y1 x2 y2  ?option value option value ...?

Options used may include generic and stroke options.

Polyline Items

Makes a multiple segment line with open ends.

pathName create polyline x1 y1 x2 y2 .... ?strokeOptions genericOptions?

Ppolygon Items

Makes a closed polygon.

pathName create ppolygon x1 y1 x2 y2 .... ?fillOptions strokeOptions genericOptions?

Prect Items

A prect is a rectangle item with optionally rounded corners. Prects are created with widget commands of the following form:

pathName create prect x1 y1 x2 y2 ?option value option value ...?

Options used may include generic, stroke, fill and the following item specific options:

-rx float

-ry float
The corner x-radius, or if -ry is not given it sets the uniform radius.

Ptext Items

Displays text as expected. Note that the x coordinate marks the baseline of the text. Gradient and image fills are now supported on GDI and Cairo. Editing not implemented. The default font is TkDefaultFont.

pathName create ptext x y ?textOptions fillOptions strokeOptions genericOptions?

The text options include:

-text string
The text string to display.

-anchor anchorPos
The position to anchor at. Defaults to sw.

-font value
The font to use.

ITEM OPTIONS

The options can be separated into a several groups, based on the nature of an item for which they apply.

Fill Options

The following fillOptions are supported:

-fill colorgrad
This is either a tk color, a gradient created with gradient create, or an image. Note images are tiled to fill the area. Currently image fills work with the cairo and gdi backends.

-fillopacity float
An opacity value between 0.0 and 1.0.

-fillrule value
Rule for filling. One of nonzero, evenodd.

Stroke Options

The following strokeOptions are supported:

-stroke color
Color of the stroked line.

-strokedasharray dashArray
List of values controlling dashed lines.

-strokelinecap value
Define the shape of the end cap of a line. The value is one of: notlast but round projecting. The default value is but.

-strokelinejoin value
Define the shape of the join for segments of a line. The value is one of: miter round bevel. The default value is round.

-strokemiterlimit float
The value applied when -strokelinejoin is miter.

-strokeopacity float
An opacitiy value between 0.0 and 1.0 to apply to the stroke.

-strokewidth float
Width of the stroked line.

Generic Options

The following genericOptions are supported:

-matrix value
A matrix is value is specified by a double list of the form

 {{a b} {c d} {tx ty}}

which is usually created with the utility function tkp::transform. See MATRIX below for details.

-parent tagOrId
The parent group. The default is id 0, which is the default group.

-state value

-style styleToken
The styleToken is a style created with pathName style create. Style options take precedence over any other options set directly (This is how SVG works).

Changes to style options are remembered, and even if an option is set back to its default, the change still takes precedence over parent item options. However, style reconfigure and itemreconfigure can be used to reset the value and clear the set mask

-tags tagList
Tags as per the Tk canvas.

GRADIENT OPTIONS

The options for gradients are:

-method value
Set method to one of pad repeat reflect. This is a partial implementation. Defaults to pad.

-stops stopSpec ?stopSpec...?
where each stopSpec is either a color or a list consisting of {offset color ?opacity?}. If an offset is given, it must be ordered and run from 0.0 to 1.0. Note that if no opacity is given, the opacity will be inherited from an item or style.

-lineartransition value
Control direction and range of gradient (valid only for linear gradiants). The form of value is {x1 y1 x2 y2} and specifies the transtion vector relative the items bounding box. Depending on -units it gets interpreted differently. If -units is bbox coordinates run from 0 to 1 and are relative the items bounding box. If -units is userspace then they are defined in absolute coordinates but in the space of the items coordinate system. It defaults to {0 0 1 0}, left to right.

-matrix value
The form of value is {{a b} {c d} {tx ty}} and sets a specific transformation for the gradient pattern only. NB: not sure about the order transforms, see -units.

-radialtransition value
Control direction and range of gradient (valid only for radial gradiants). The form of value is {cx cy ?r? ?fx fy?} and specifies the transition circles relative the items bounding box and run from 0 to 1. They default to {0.5 0.5 0.5 0.5 0.5}. cx,cy is the center of the end circle and fx,fy the center of the start point.

-units value
The value is one of bbox or userspace and sets the units of the transition coordinates. See above. Defaults to bbox.

MATRIX

Each tkpath item has a -matrix option which defines the local coordinate system for that item.

Matrix Generation

The easiest way to generate a -matrix value is using the utility function tkp::transform.

The following transforms are available:

tkp::transform rotate angle ?centerX centerY?
Create a rotation matrix.

tkp::transform scale factorXY ?factorY?
Create a scaling matrix for resizing items.

tkp::transform skewx angle
Create a x skew matrix.

tkp::transform skewy angle
Create a y skew matrix.

tkp::transform translate x y
Create a translation matrix.

Matrix Inheritance

Inheritance for the -matrix option works differently than for the other options. Instead of just being overwritten, all -matrix options are applied starting from the root, down through any number of nested group items, to the actual item being displayed.

Matrix Details

A matrix is defined as a double list {{a b} {c d} {tx ty}}.

Following are the general forms for -matrix:

{{sx 0} {0 sy} {0 0}}
A simple scaling matrix.

{{1 0} {0 1} {tx ty}}
A translation matrix.

{{cos(a) sin(a)} {-sin(a) cos{a}} {0 0}}
Rotation around origin with an angle 'a'.

SURFACES

Creates an in memory drawing surface. It returns a token which is a new command.

The available surface commands are:

tkp::surface new width height
Create a new surface token command.

tkp::surface names
lists the existing surface tokens.

Surface Token Commands

The surface token commands are:

$token copy imageName
copies the surface to an existing image (photo) and returns the name of the image so you can do:

set image [$token copy [image create photo]]

See Tk_PhotoPutBlock for how it affects the existing image.

The boolean variable tkp::premultiplyalpha controls how the copy action handles surfaces with the alpha component premultiplied. If 1 the copy process correctly handles any format with premultiplied alpha. This gets the highest quality for antialiasing and correct results for partial transparency. It is also slower. If 0 the alpha values are not remultiplied and the result is wrong for transparent regions, and gives poor antialiasing effects. But it is faster. The default is 1.

$token create type coords ?options?
draws the item of type to the surface. All item types except the group and the corresponding options as described above are supported, except the canvas specific -tags and -state. This is the only place we can use gradients created with tkp::gradient.

$token destroy
destroys surface.

$token erase x y width height
erases the indicated area to transparent.

$token height

$token width
Returns height and width respectively.

Note that the surface behaves different from the canvas widget. When you have put an item there there is no way to configure it or to remove it. If you have done a mistake then you have to erase the complete surface and start all over. Better to experiment on the canvas and then reproduce your drawing to a surface when you are satisfied with it. Also, surfaces do not support named gradients or styles.

NB: gdi+ seems unable to produce antialiasing effects here. But there seems to be no gdi+ specific way of drawing in memory bitmaps but to call CreateDIBSection() which is a Win32 GDI API.

MISCELLANEOUS

Antialiasing

Antialiasing, if available, is controlled by the variable tkp::antialias. Switch on with:

set tkp::antialias 1

Pixelalign

The command tkp::pixelalign says how the platform graphics library draw when we specify integer coordinates. Some libraries position a one pixel wide line exactly at the pixel boundaries, and smears it out, if antialiasing, over the adjecent pixels. This can look blurred since a one pixel wide black line suddenly becomes a two pixel wide grey line. It seems that cairo and quartz (MacOSX) do this, while gdi+ on Windows doesn't. This command just provides the info for you so you may take actions. Either you can manually position lines with odd integer widths at the center of pixels (adding 0.5), or set the ::tkp::depixelize to 1, see below.

Depixelize

If the boolean variable ::tkp::depixelize is set to 1, try to adjust coordinates for objects with integer line widths so that lines are depixelized.

VISIBLE DIFFERENCES

The following commands diverge from the standard canvas:

delete
Calls to delete all will silently ignore the root item.

lower/raise
Movement is constrained to siblings. If reference tagOrId not given it defaults to first/last item of the root items children. Items which are not siblings to the reference tagOrId are silently ignored. Good or bad?

find above/below
is constrained to siblings. Good or bad?

scale/move
if you apply scale or move on a group item it will apply this to all its descendants, also to child group items in a recursive way.

tag all
Note that this presently also includes the root item which can result in some unexpected behavior. In many case you can operate on the root item (0) instead. As an example, if you want to move all items in canvas, then do:

pathName move 0 x y
and similar for scale etc.

KNOWN ISSUES

Postscript is not implemented.

Implementors should see the TODO file and comments in the C sources marked with @@@.

FURTHER DOCUMENTATION

See http://www.w3.org/TR/SVG11/ and http://cairographics.org.

COPYRIGHT

Copyright (c) 2005-2008 Mats Bengtsson using a BSD style license.

Copyright (c) 2011 Peter MacDonald

Copyright ¨Ï 1995-1997 Roger E. Critchlow Jr. Copyright ¨Ï 1992-1994 The Regents of the University of California. Copyright ¨Ï 1994-1996 Sun Microsystems, Inc. Copyright ¨Ï 1997-1999 Scriptics Corporation.