Skip to content

WebCanvas Text Alignment

Why doesn’t the WebGraphics class have a StringWidth method?

Good question! The answer lies in the fact that web applications “run” in two different places simultaneously – Xojo code in your app and Javascript code in the user’s browser. Let’s take this code for a desktop Canvas Paint event for centering some text as an example:

Dim txt as String = "Hello World"
Dim y as Integer = 100
Dim AlignX as Integer = g.Width/2
Dim w as Integer = g.StringWidth(txt)
Dim x as Integer = (AlignX-w)/2
g.DrawString txt,x,y

If you were trying to do this with a WebCanvas, the problem is the call to g.StringWidth. That would need to call out to the browser to get the result because that’s where the physical canvas and the HTML5 rendering engine actually is. Since calls to/from the browser are asynchronous, you wouldn’t be able to get the result back until some time in the future, long after your drawing code has run.

The solution we provided is a rather simple one. Why not tell the canvas what type of alignment you want…

Dim txt as String = "Hello World"Dim y as Integer = 100
Dim AlignX as Integer = g.Width/2
g.TextAlignment = WebGraphics.TextAlignmentCenter
g.DrawString txt,AlignX,y

The Xojo Framework does the math for you right on the browser! The TextAlignment property supports Left, Center and Right alignment so you don’t need to know the width of the string to calculate alignment any more.

Want to do Decimal alignment? Convert the currency to a string and split it into the text that needs to draw on the left and the text that needs to draw on the right of the decimal point, and draw it in two pieces, like this:

Dim c as currency = 15.32dim parts() as String = Split(Str(c,"0.00"),".")
Dim y as Integer = 100
Dim AlignX as Integer = g.Width/2
g.TextAlignment = WebGraphics.TextAlignmentRight
g.DrawString Parts(0)+".", AlignX, yg.TextAlignment = WebGraphics.TextAlignmentLeftg.DrawString Parts(1), AlignX, y

As you can see, the TextAlignment property gives you a lot of flexibility without needing to know the actual width of the string you are drawing.