GPanel#

How GPanel is set up#

GPanel runs in the Pyodide worker and draws with PixiJS on an OffscreenCanvas. The canvas, the mouse and keyboard events and the audio are provided by the host bridge (src/pyodide/host_bridge/), which is set up automatically when a program imports gpanel (see System architecture).

Basic GPanel Program#

Every GPanel code has to start with makeGPanel. This function sets up the required settings to be able to draw on the canvas with the other functions.

It is advisable to import everything making development easier.

from gpanel import *
makeGPanel()

GPanel Functions#

Extensive list of all exposed functions which can be used from GPanel.

General Functions#

  • makeGPanel(*args, **kwargs): Constructs a GPanel in the browser canvas.

    GPanel can be initialized in multiple ways:

    • No arguments: Initialized with the x/y range (0…1, 0…1)

    • Size object: Initialized with given canvas size and x/y range (0…width, 0…height)

      • Example: makeGPanel(Size(300, 200))

    • xmin, xmax, ymin, ymax: Initialized with the x/y range (xmin…xmax, ymin…ymax)

      • Example: makeGPanel(-10, 10, -10, 10)

    Event callbacks can be passed as keyworded arguments. For example: makeGPanel(-5, 5, -100, 10, mouseClicked=callback)

    Valid callbacks:

    • mousePressed: Takes 0 or 2 arguments (x, y)

    • mouseReleased: Takes 0 or 2 arguments (x, y)

    • mouseClicked: Takes 0 or 2 arguments (x, y)

    • mouseSingleClicked (same as mouseClicked): Takes 0 or 2 arguments (x, y)

    • mouseDragged: Takes 0 or 2 arguments (x, y)

    • mouseMoved: Takes 0 or 2 arguments (x, y)

    • mouseEntered: Takes 0 or 2 arguments (x, y)

    • mouseExited: Takes 0 or 2 arguments (x, y)

    • mouseDoubleClicked: Takes 0 or 2 arguments (x, y)

    • keyPressed: Takes 0 or 1 argument (key)

    • keyReleased: Takes 0 or 1 argument (key)

    The (x,y) coordinates are float values of where the mouse was in GPanel coordinates. The key argument is the key that was pressed as a string.

    If GPanel seems to start lagging quite quickly, one can additionally add a lower graphicsLimit (defaults to 100). This can be added with makeGPanel(..., graphicsLimit=100). Reducing this value results in GPanel flattening the image more often.

  • getScreenWidth(): Gets the current screen width in pixels.

  • getScreenHeight(): Gets the current screen height in pixels.

  • window(xmin, xmax, ymin, ymax): Modifies the existing coordinate system by adjusting the scale used for new drawings. Pre-existing drawings will not be updated. Flipping ymin and ymax so that ymin > ymax flips the point of orign to be in the top left instead of bottom left of the canvas.

  • flattenGraphics(): Optimizes the currently drawn graphics by flattening them into a single sprite. Is executed automatically, but can be executed manually if required for testing or performance purposes.

  • drawGrid(*args): Draws grid lines on the canvas.

    • drawGrid(x1, x2, y1, y2): Draws grid in area (x1…x2, y1…y2) with 10 cells in x- and y-direction

    • drawGrid(x1, x2, y1, y2, color): Same, but in the given color. Color should be a x11 color code, a hexadecimal or a Color object.

    • drawGrid(x1, x2, y1, y2, xCells, yCells): Draws grid in area (x1…x2, y1…y2) with xCells cells in x-direction and yCells in y-direction.

    • drawGrid(x1, x2, y1, y2, xCells, yCells, color): Same, but in the given color.

  • makeColor(value, alpha=1.0): Creates and returns a color. Supported color values build on top of PIXI Color Sources.

    The alpha argument (optional) has to be a float between 0.0 and 1.0

    Accepted parameters:

    • string: String of the x11 color (“red”, “yellow”, etc.). Extensive list of colors

    • hex of color as string

    • int of color

    • [int, int, int]: Integer list/tuple with values 0-255

    • [float, float, float]: Float list/tuple with values 0-1

    • [int, int, int], alpha or [float, float, float], alpha: Additional alpha value for slightly a slightly transparent color.

    • r, g, b: Red, Green, Blue as integer or float.

    • r, g, b, alpha: Red, Green, Blue, Alpha. Alpha has to be a float.

    Examples of legal inputs:

    • "red"

    • "7FFED4"

    • 0x7FFED4

    • 8388564

    • (0.5, 1.0, 0.83)

    • (128, 255, 212)

  • drawPanelGrid(p, *args): Same as drawGrid(*args), but draws on the GPanel p returned by makeGPanel.

  • windowSize(width, height) or resize(width, height): Changes the size of the canvas in pixels.

  • title(text): Sets the title of the GPanel tab.

  • addStatusBar(height): Adds a status bar with the given height (in pixels) at the bottom of the window.

  • setStatusText(text, font=None, color=None): Displays the text in the status bar. The old text is erased.

  • windowPosition(ulx, uly): Exists for compatibility with TigerJython, but is not implemented in WebTigerPython and raises a NotImplementedError.

  • enableRepaint(enable): Turns automatic rendering after every drawing command on (True) or off (False). With automatic rendering turned off, repaint() renders all changes at once, which is useful for animations.

  • repaint(): Renders the current drawing. Only needed if automatic rendering is turned off.

  • dispose(): Closes the GPanel tab.

  • isDisposed(): Returns whether the GPanel has been closed.

  • quit(): Releases the GPanel. Drawing functions can only be used again after a new makeGPanel().

  • delay(time): Stops the program execution for time milliseconds.

  • clear(): Clears the screen, resets the background color, and moves the cursor back to (0,0).

  • erase(): Clears the screen and resets the background color. Does not reset the cursor. Use clear for that.

Drawing Functions#

  • lineWidth(width: int | float) or setPenSize(width: int | float): Sets the current pen size (width) (>=1). Returns the previous pen size.

  • bgColor(*args) or setBgColor(*args): Sets the background color of the canvas. Valid inputs include any valid value input for the makeColor function plus Color objects created from makeColor.

  • setColor(*args): Sets the color used for drawing lines and filling shapes.

    Valid inputs include any valid value input for the makeColor function plus Color objects created from makeColor.

  • move(*args) or pos(*args): Sets the current graph cursor position to given user coordinates (without drawing anything).

    Accepted parameters:

    • x, y

    • [x, y]

    • (x, y)

    • complex(x, y)

  • getPosX(): Gets the x coordinate of the cursor.

  • getPosY(): Gets the y coordinate of the cursor.

  • getPos(): Gets the (x, y) coordinates of the cursor as a tuple.

  • draw(*args): Draws a line to the given point and moves the cursor to the point.

    Parameters:

    • x, y or (x, y) or [x, y] or complex(x, y): Draws line and moves to coordinates (x, y).

    • [[x1, y1], ..., [xn, yn]]: Draws multiple lines from one coordinate to the next. Cursor ends on (xn, yn).

  • line(*args): Draws a line from (x1, y1) to (x2, y2) without adjusting the cursor.

    Accepted parameters:

    • x1, y1, x2, y2

    • [x1, y1], [x2, y2]

    • (x1, y1), (x2, y2)

    • complex(x1, y1), complex(x2, y2)

  • circle(radius): Draws a circle outline at the current position with the given radius.

  • fillCircle(radius): Draws a filled circle at the current position with the given radius.

  • ellipse(a, b): Draws an ellipse outline with the given semi-major length (a = width / 2) and semi-minor axis (b = height / 2).

  • fillEllipse(a, b): Draws a filled ellipse with the given semi-major length (a = width / 2) and semi-minor axis (b = height / 2).

  • rectangle(*args): Draws a rectangle outline.

    Parameters:

    • w, h: Draws a rectangle with the width w, height h and the center point on the cursor.

    • x1, y1, x2, y2 or [x1, y1], [x2, y2] or complex(x1, y1), complex(x2, y2): Draws a rectangle from the corner (x1, y1) to (x2, y2).

  • fillRectangle(*args): Draws a filled rectangle.

    Parameters:

    • w, h: Draws a rectangle with the width w and height h and the center point on the cursor.

    • x1, y1, x2, y2 or [x1, y1], [x2, y2] or complex(x1, y1), complex(x2, y2): Draws a rectangle from the corner (x1, y1) to (x2, y2).

  • arc(radius, startAngle, extendAngle): Draws an arc outline around a radius wide circle from the given startAngle to the extendAngle. The angle is in degrees. The start (0) is to the east. Positive is counterclockwise.

    arc(0.5, 0, 360) is equivalent to circle(0.5).

  • fillArc(radius, startAngle, extendAngle): Draws a filled arc around a radius wide circle from the given startAngle to the extendAngle. The angle is in degrees. The start (0) is to the east. Positive is counterclockwise.

    fillArc(0.5, 0, 360) is equivalent to fillCircle(0.5).

  • polygon(*args): Draws a polygon outline with each set of coordinates being a vertex.

    Accepted parameters:

    • [[x1, y1], ..., [xn, yn]]

    • [complex(x1, y1), ..., (complex(xn, yn))]

    • [[x1, ..., xn], [y1, ..., yn]]

  • fillPolygon(*args): Draws a filled polygon with each set of coordinates being a vertex.

    Accepted parameters:

    • [[x1, y1], ..., [xn, yn]]

    • [complex(x1, y1), ..., (complex(xn, yn))]

    • [[x1, ..., xn], [y1, ..., yn]]

  • quadraticBezier(*args): Draws a quadratic bezier line with the start point (x1, y1), control point (xc, yc), and end point (x2, y2).

    Accepted parameters:

    • x1, y1, xc, yc, y2, x2

    • [x1, y1], [xc, yc], [y2, x2]

    • complex(x1, y1), complex(xc, yc), complex(y2, x2)

  • cubicBezier(*args): Draws a cubic bezier line with the start point (x1, y1), control points (xc1, yc1) and (xc2, yc2), and end point (x2, y2).

    Accepted parameters:

    • x1, y1, xc1, yc1, xc2, yc2, y2, x2

    • [x1, y1], [xc1, yc1], [xc2, yc2], [y2, x2]

    • complex(x1, y1), complex(xc1, yc1), complex(xc2, yc2), complex(y2, x2)

  • triangle(*args): Draws a triangle outline with the given three points (x1, y1), (x2, y2), (x3, y3).

    Accepted parameters:

    • x1, y1, x2, y2, x3, y3

    • [x1, y1], [x2, y2], [x3, y3]

    • complex(x1, y1), complex(x2, y2), complex(x3, y3)

  • fillTriangle(*args): Draws a filled triangle with the given three points (x1, y1), (x2, y2), (x3, y3).

    Accepted parameters:

    • x1, y1, x2, y2, x3, y3

    • [x1, y1], [x2, y2], [x3, y3]

    • complex(x1, y1), complex(x2, y2), complex(x3, y3)

  • fill(*args): Performs flood fill on a given coordinates (x, y).

    Coordinate can be given as x, y, (x, y), [x, y], complex(x, y).

    Parameter variations:

    • Coordinate, color: Replaces all touching pixels that are the same color as the starting pixel with the given color.

    • Coordinate, colorToReplace, color: Replaces all touching pixels that are the same color as colorToReplace with color. If the given coordinate (x, y) is not colorToReplace, nothing happens.

  • getPixelColor(*args): Returns the Color object for the given coordinates (x, y).

    Accepted parameters:

    • x, y

    • (x, y)

    • [x, y]

    • complex(x, y)

  • getPixelColorStr(*args): Same as getPixelColor, but returns the color as a string.

  • point(*args): Draws a single pixel at the given coordinates (x, y). Accepts the same coordinate formats as getPixelColor.

  • image(path, x, y): Draws an image with its lower left corner at (x, y).

    path can be

    • a file of the workspace, e.g. "img/logo.png" (see Multi-File System)

    • an image of the bundled TigerJython sprites, e.g. "sprites/pony_1.gif"

    • a URL starting with http:// or https://. The server has to allow cross-origin requests (CORS).

    Images are drawn at the size they would have in TigerJython, where the default GPanel window is 600 pixels wide. They are scaled together with the canvas.

  • getImage(path): Returns a reference to the image at path that can be passed to image.

Coordinate Conversion#

These functions convert between pixels of an image and the user coordinates set with makeGPanel or window. Like images, they use the TigerJython reference size of the window (600 pixels, or the size given with Size).

  • toWindowX(pixelX), toWindowY(pixelY): Convert a pixel position to user coordinates.

  • toWindowWidth(pixelWidth), toWindowHeight(pixelHeight): Convert a size in pixels to user coordinates.

  • toUserX(x), toUserY(y): Convert a position in user coordinates to pixels.

  • toUserWidth(width), toUserHeight(height): Convert a size in user coordinates to pixels.

from gpanel import *
makeGPanel(0, 10, 0, 10)
image("sprites/pony_1.gif", 2, 2)
# draw a rectangle around the image
w = toWindowWidth(200)  # the image is 200 x 200 pixels
h = toWindowHeight(200)
rectangle(2, 2, 2 + w, 2 + h)

Text Functions#

  • makeFont(name="Arial", style=0, size=12): Creates and returns a Font object.

    Parameters (all optional):

    • name: A string value of the font name. Needs to be a web font available in your browser. Defaults to "Arial".

    • style: The specific style (bold, italic) the font should have. Accepted combinations are Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Font.ITALIC. Defaults to Font.PLAIN.

    • size: The size of the text as an integer. Defaults to 12.

  • text(*args): Draws text at the given coordinates, color and style.

    Coordinates can be given as x, y, (x, y), [x, y], complex(x, y).

    Parameter variations:

    • text: Text is drawn at the current cursor position.

    • Coordinates, text: Text is drawn at (x, y).

    • Coordinates, text, font, textColor, backgroundColor: Text is drawn at (x, y) with the given Font (read makeFont), textColor and backgroundColor (read makeColor)

Callbacks#

Instead of passing the callbacks to makeGPanel, they can also be registered with the decorators @mousePressed, @mouseReleased, @mouseClicked, @mouseSingleClicked, @mouseDoubleClicked, @mouseDragged, @mouseMoved, @mouseEntered, @mouseExited, @keyPressed, @keyReleased, @keyCodePressed and @keyCodeReleased:

from gpanel import *
makeGPanel()

@mousePressed
def onPress(x, y):
    move(x, y)
    fillCircle(0.02)

Inside a mouse callback, isLeftMouseButton() and isRightMouseButton() return which mouse button was used.

  • addKeyPressListener(cb): Adds the given function as a callback to key-press (key-down) events.

    Callback can take 0 arguments or 1 string argument to receive the pressed key.

  • addKeyReleaseListener(cb): Adds the given function as a callback to key-release (key-up) events.

    Callback can take 0 arguments or 1 string argument to receive the pressed key.

  • addMouseDragListener(cb): Adds the given function as a callback to mouse-drag events.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMousePressListener(cb): Adds the given function as a callback to mouse-press (mouse-down) events.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMouseReleaseListener(cb): Adds the given function as a callback to mouse-release (mouse-up) events.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMouseClickListener(cb): Adds the given function as a callback to mouse-click events.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMouseDoubleClickListener(cb): Adds the given function as a callback to mouse-double-click events.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMouseMoveListener(cb): Adds the given function as a callback to mouse-move events.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMouseEnterListener(cb): Adds the given function as a callback to when the mouse enters the canvas.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

  • addMouseExitListener(cb): Adds the given function as a callback to when the mouse leaves the canvas.

    Callback can take 0 arguments or 2 float arguments to receive the GPanel coordinates of the mouse.

Keyboard#

  • isKeyPressed(keycode): Returns if a given key is currently pressed.

    The given parameter keycode can be of type string to depict a specific key or an int to depict the code value of a character.

  • isKeyCodePressed(keycode): Same as isKeyPressed.

  • getKey(): Returns the key of the last pressed key as a string. Returns “” if no key has been pressed yet or an illegal key is entered.

    A single key can only be fetched once:

    getKey()
    getKey()
    

    The second call will result in "" if no key was pressed between the two function calls.

  • getKeyCode(): Returns the key code of the last pressed key as an int. Returns 0 if no key has been pressed yet.

    A single key can only be fetched once:

    getKeyCode()
    getKeyCode()
    

    The second call will result in 0 if no key was pressed between the two function calls.

  • getKeyWait(): Waits until a key is pressed and returns the corresponding key.

  • getKeyCodeWait(): Waits until a key is pressed and returns the corresponding key code.

  • kbhit(): Returns a boolean whether getKey() or getKeyCode() will return a key, i.e. there is a key to be collected.

Classes#

These are the classes which are exported and can be worked with. Some functions return or accept these objects.

  • Color: Returned from makeColor. Printing a Color object displays the RGBA values of the color.

  • X11Color: Helpers for X11 color names: X11Color.toColor("red") returns the Color of a color name, X11Color.getColorNames() returns all known color names, and X11Color.getRandomColor() / getRandomX11Color() return a random color.

  • Size: To be passed in when calling makeGPanel to initialize a fixed canvas size. Takes a width and height parameter when created: Size(width, height).

  • Font: Returned from makeFont. Has the three constants Font.PLAIN, Font.BOLD, and Font.ITALIC to be passed in when creating a font. Used for displaying styled text in the text function.