scallop dome pyformex logo

Previous topic

24. gluttext — 2D text decorations using GLUT fonts

Next topic

26. viewport — Interactive OpenGL Canvas embedded in a Qt4 widget.

[FSF Associate Member]

Valid XHTML 1.0 Transitional

25. canvas — This implements an OpenGL drawing widget for painting 3D scenes.

Classes defined in module canvas

class canvas.ActorList(canvas)

A list of drawn objects of the same kind.

This is used to collect the Actors, Decorations and Annotations in a scene. Currently the implementation does not check that the objects are of the proper type.


Add an actor or a list thereof to a ActorList.


Remove an actor or a list thereof from an ActorList.


Redraw all actors in the list.

This redraws the specified actors (recreating their display list). This could e.g. be used after changing an actor’s properties.

class canvas.CanvasSettings(**kargs)

A collection of settings for an OpenGL Canvas.

The canvas settings are a collection of settings and default values affecting the rendering in an individual viewport. There are two type of settings:

  • mode settings are set during the initialization of the canvas and can/should not be changed during the drawing of actors and decorations;
  • default settings can be used as default values but may be changed during the drawing of actors/decorations: they are reset before each individual draw instruction.

Currently the following mode settings are defined:

  • bgmode: the viewport background color mode
  • bgcolor: the viewport background color: a single color or a list of colors (max. 4 are used).
  • bgimage: background image filename
  • slcolor: the highlight color
  • alphablend: boolean (transparency on/off)

The list of default settings includes:

  • fgcolor: the default drawing color
  • bkcolor: the default backface color
  • colormap: the default color map to be used if color is an index
  • bklormap: the default color map to be used if bkcolor is an index
  • smooth: boolean (smooth/flat shading)
  • lighting: boolean (lights on/off)
  • culling: boolean
  • transparency: float (0.0..1.0)
  • avgnormals: boolean
  • wiremode: integer -3..3
  • pointsize: the default size for drawing points
  • marksize: the default size for drawing markers
  • linewidth: the default width for drawing lines

Any of these values can be set in the constructor using a keyword argument. All items that are not set, will get their value from the configuration file(s).


Reset the CanvasSettings to its defaults.

The default values are taken from the configuration files. An optional dictionary may be specified to override (some of) these defaults.

update(d, strict=True)

Update current values with the specified settings

Returns the sanitized update values.

classmethod checkDict(clas, dict, strict=True)

Transform a dict to acceptable settings.


Activate the mode canvas settings in the GL machine.


Activate the default canvas settings in the GL machine.

get(key, default)

Return the value for key or a default.

This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.

setdefault(key, default)

Replaces the setdefault function of a normal dictionary.

This is the same as the get method, except that it also sets the default value if get found a KeyError.

class canvas.Canvas(settings={})

A canvas for OpenGL rendering.

The Canvas is a class holding all global data of an OpenGL scene rendering. This includes colors, line types, rendering mode. It also keeps lists of the actors and decorations in the scene. The canvas has a Camera object holding important viewing parameters. Finally, it stores the lighting information.

It does not however contain the viewport size and position.


Toggle lights on/off.


Return the status of the lighting.


Return all the settings to their default values.


Set the global ambient lighting for the canvas


Set the default material light properties for the canvas


Change the light parameters

setRenderMode(mode, lighting=None)

Set the rendering mode.

This sets or changes the rendermode and lighting attributes. If lighting is not specified, it is set depending on the rendermode.

If the canvas has not been initialized, this merely sets the attributes self.rendermode and If the canvas was already initialized (it has a camera), and one of the specified settings is fdifferent from the existing, the new mode is set, the canvas is re-initialized according to the newly set mode, and everything is redrawn with the new mode.

setWireMode(state, mode=None)

Set the wire mode.

This toggles the drawing of edges on top of 2D and 3D geometry. Value is an integer. If positive, edges are shown, else not.

setToggle(attr, state)

Set or toggle a boolean settings attribute

Furthermore, if a Canvas method do_ATTR is defined, it will be called with the old and new toggle state as a parameter.

do_lighting(state, oldstate=None)

Toggle lights on/off.


Set the linewidth for line rendering.

setLineStipple(repeat, pattern)

Set the linestipple for line rendering.


Set the size for point drawing.

setBackground(color=None, image=None)

Set the color(s) and image.

Change the background settings according to the specified parameters and set the canvas background accordingly. Only (and all) the specified parameters get a new value.


  • color: either a single color, a list of two colors or a list of four colors.
  • image: an image to be set.

Create the background object.


Set the default foreground color.


Set the highlight color.

setTriade(on=None, pos='lb', siz=100)

Toggle the display of the global axes on or off.

If on is True, a triade of global axes is displayed, if False it is removed. The default (None) toggles between on and off.


Clear the canvas to the background color.


Activate the canvas settings in the GL machine.


Override some settings


Initialize the rendering machine.

The rendering machine is initialized according to self.settings: - self.rendermode: one of -


Flush all OpenGL commands, making sure the display is updated.


(Re)display all the actors in the scene.

This should e.g. be used when actors are added to the scene, or after changing camera position/orientation or lens.


Set up the canvas for 2D drawing on top of 3D canvas.

The 2D drawing operation should be ended by calling end_2D_drawing. It is assumed that you will not try to change/refresh the normal 3D drawing cycle during this operation.


Cancel the 2D drawing mode initiated by begin_2D_drawing.


Return the bbox of all actors in the scene


Set the bounding box of the scene you want to be visible.

bb is a (2,3) shaped array specifying a bounding box. If no bbox is given, the bounding box of all the actors in the scene is used, or if the scene is empty, a default unit bounding box.


Add a 3D actor or a list thereof to the 3D scene.


Add a highlight or a list thereof to the 3D scene.


Add an annotation or a list thereof to the 3D scene.


Add a 2D decoration or a list thereof to the canvas.


Add any item or list.

This will add any actor/annotation/decoration item or a list of any such items to the canvas. This is the prefered method to add an item to the canvas, because it makes sure that each item is added to the proper list. It can however not be used to add highlights.

If you have a long list of a single type, it is more efficient to use one of the type specific add methods.


Remove a 3D actor or a list thereof from the 3D scene.

Without argument, removes all actors from the scene. This also resets the bounding box for the canvas autozoom.


Remove a highlight or a list thereof from the 3D scene.

Without argument, removes all highlights from the scene.


Remove an annotation or a list thereof from the 3D scene.

Without argument, removes all annotations from the scene.


Remove a 2D decoration or a list thereof from the canvas.

Without argument, removes all decorations from the scene.


Remove a list of any actor/highlights/annotation/decoration items.

This will remove the items from any of the canvas lists in which the item appears. itemlist can also be a single item instead of a list. If None is specified, all items from all lists will be removed.


Redraw all actors in the scene.

setCamera(bbox=None, angles=None)

Sets the camera looking under angles at bbox.

This function sets the camera parameters to view the specified bbox volume from the specified viewing direction.


  • bbox: the bbox of the volume looked at
  • angles: the camera angles specifying the viewing direction. It can also be a string, the key of one of the predefined camera directions

If no angles are specified, the viewing direction remains constant. The scene center (camera focus point), camera distance, fovy and clipping planes are adjusted to make the whole bbox viewed from the specified direction fit into the screen.

If no bbox is specified, the following remain constant: the center of the scene, the camera distance, the lens opening and aspect ratio, the clipping planes. In other words the camera is moving on a spherical surface and keeps focusing on the same point.

If both are specified, then first the scene center is set, then the camera angles, and finally the camera distance.

In the current implementation, the lens fovy and aspect are not changed by this function. Zoom adjusting is performed solely by changing the camera distance.

project(x, y, z, locked=False)

Map the object coordinates (x,y,z) to window coordinates.

unProject(x, y, z, locked=False)

Map the window coordinates (x,y,z) to object coordinates.

zoom(f, dolly=True)

Dolly zooming.

Zooms in with a factor f by moving the camera closer to the scene. This does noet change the camera’s FOV setting. It will change the perspective view though.

zoomRectangle(x0, y0, x1, y1)

Rectangle zooming.

Zooms in/out by changing the area and position of the visible part of the lens. Unlike zoom(), this does not change the perspective view.

x0,y0,x1,y1 are pixel coordinates of the lower left and upper right corners of the area of the lens that will be mapped on the canvas viewport. Specifying values that lead to smaller width/height will zoom in.

zoomCentered(w, h, x=None, y=None)

Rectangle zooming with specified center.

This is like zoomRectangle, but the zoom rectangle is specified by its center and size, which may be more appropriate when using off-center zooming.


Rectangle zoom to make full scene visible.


Save the current OpenGL buffer


Show the saved buffer

draw_focus_rectangle(ofs=0, color=(1.0, 0.2, 0.4))

Draw the focus rectangle.

The specified width is HALF of the line width

draw_cursor(x, y)

draw the cursor


Set the list of actors inside the pick_window.

pick_parts(obj_type, max_objects, store_closest=False)

Set the list of actor parts inside the pick_window.

obj_type can be ‘element’, ‘face’, ‘edge’ or ‘point’. ‘face’ and ‘edge’ are only available for Mesh type geometry. max_objects specifies the maximum number of objects

The picked object numbers are stored in self.picked. If store_closest==True, the closest picked object is stored in as a tuple ( [actor,object] ,distance) in self.picked_closest

A list of actors from which can be picked may be given. If so, the resulting keys are indices in this list. By default, the full actor list is used.


Set the list of actor elements inside the pick_window.


Set the list of actor points inside the pick_window.


Set the list of actor edges inside the pick_window.


Set the list of actor faces inside the pick_window.


Return the numbers inside the pick_window.


Highlight an actor in the scene.


Highlight a selection of actors on the canvas.

K is Collection of actors as returned by the pick() method. colormap is a list of two colors, for the actors not in, resp. in the Collection K.


Highlight a selection of actor elements on the canvas.

K is Collection of actor elements as returned by the pick() method. colormap is a list of two colors, for the elements not in, resp. in the Collection K.


Highlight a selection of actor edges on the canvas.

K is Collection of TriSurface actor edges as returned by the pick() method. colormap is a list of two colors, for the edges not in, resp. in the Collection K.


Highlight a selection of actor elements on the canvas.

K is Collection of actor elements as returned by the pick() method.


Highlight a selection of partitions on the canvas.

K is a Collection of actor elements, where each actor element is connected to a collection of property numbers, as returned by the partitionCollection() method.

highlight(K, mode)

Highlight a Collection of actor/elements.

K is usually the return value of a pick operation, but might also be set by the user. mode is one of the pick modes.

Functions defined in module canvas


Return a list of the 2nd numbers in the openGL pick buffer.

canvas.glLineStipple(factor, pattern)

Set the line stipple pattern.

When drawing lines, OpenGl can use a stipple pattern. The stipple is defined by two values: a pattern (on/off) of maximum 16 bits, used on the pixel level, and a multiplier factor for each bit.

If factor <= 0, the stippling is disabled.


Enable smooth shading


Disable smooth shading


Convert On/Off strings to a boolean

canvas.glEnable(facility, onoff)

Enable/Disable an OpenGL facility, depending on onoff value

facility is an OpenGL facility. onoff can be True or False to enable, resp. disable the facility, or None to leave it unchanged.


Split a dict in canvas settings and other items.

Returns a tuple of two dicts: the first one contains the items that are canvas settings, the second one the rest.