Web Canvas

From Xojo Documentation

The Canvas control can be used to display a picture from a file (or in the project) or graphics drawn in code. The Canvas control has access to the drawing tools belonging to the WebGraphics class; with these tools you can programmatically draw objects within the Canvas. If your app requires a type of control that is not built-in, you can use a Canvas control and Graphics drawing commands to create the controls you need.

Below are commonly used events and methods for Canvas. Refer to the Language Reference for WebCanvas for the complete list.


Paint - The Paint event is called when the Canvas needs to redraw itself. This could be called automatically by the web browser or by a call to Refresh. Use the supplied web graphics object (g) for all Canvas drawing.


Invalidate - Call this method to tell the web browser to redraw the Canvas when it is doing other redrawing.

Refresh - Call this method to immediately redraw the Canvas. You can optionally specify a parameter to erase the background before redrawing. Calling this method frequently can slow your app. In most cases it is better to call Invalidate instead.

Web Graphics

The Paint event supplies a WebGraphics object (g) as a parameter that you use to draw to the Canvas. WebGraphics contains properties and methods for drawing.

Below are some common properties and methods that are available:


DrawingColor - Specifies the color that will be used for all drawing and fill methods.

FontName, FontSize - Specifies the text font and size used by the DrawText method.


DrawLine - Draws a line using the ForeColor.

DrawOval, FillOval - Draws an empty or filled Oval using the ForeColor.

DrawPicture - Draws a picture that is either in the project or has been loaded from the drive into a Picture object.

DrawRectangle, FillRectangle - Draws a empty or filled rectangle using the ForeColor.

DrawText - Draws string text using the DrawingColor, FontName and FontSize.


This code in the Canvas Paint event handler draws a shape and some text in the Canvas:

g.DrawingColor = Color.Blue
g.FillRectangle(10, 10, 50, 50)

g.DrawingColor = Color.Green
g.Drawtext("Hello!", 50, 100)

This code below in the Paint event draws 50 of boxes at random locations with random colors:

// Boxes
g.ClearRectangle(0, 0, g.Width, g.Height)

Var x, y As Integer
Var w, h As Integer
Var c As Color

For i As Integer = 1 To 50
c = RGB(Rnd * 255, Rnd * 255, Rnd * 255)

x = Rnd * g.Width + 1
y = Rnd * g.Height + 1
w = Rnd * g.Width \ 2 + 1
h = Rnd * g.Height \ 2 + 1

g.DrawingColor = c
g.FillRectangle(x, y, w, h)

Example Projects

These example project demonstrate various ways a Canvas can be used:

  • Examples/Web/Graphics/CanvasBoxes
  • Examples/Web/Graphics/CanvasClock

See Also

WebCanvas class