Sunday , 16 December 2018
Home / Programming / JavaScript / Text API – Advanced JavaScript Tutorial
Text API
Text API

Text API – Advanced JavaScript Tutorial

In this tutorial, we’ll take a look at how to add text to our canvas. It’s actually quite simple. You’re given many options to set up how the text appears.

Let’s update our script to this.

There are 2 methods to add text to the canvas. They are the fillText() and strokeText() methods. Both of these methods have the same parameters. The first parameter is the string you want to write into the canvas. The second parameter is the x coordinate. The third parameter is the y coordinate. There is also a fourth parameter for the maximum width of the text both. If you update the fillText() method to this.

Then you’ll notice our text is all scrunched up. This is because the maximum width is only 20 pixels and so there’s not a lot of room for the text to breath. The difference between the fillText() and strokeText() methods is that the fillText() method uses the fillStyle property as the color and the strokeTexT() method uses the strokeStyle property as the color.

These methods can be used on their own, but there is a way to change the font, size, and alignment with 3 properties available to you in the 2D context.

Update your script to this.

Let’s go over each property

  • font – This property allows you to manipulate the style, size, and font used in the text. You don’t have to define all 3, but it works similar to CSS. You can just pass in Verdana and all will be fine.
  • textAlign – This property allows you to align the text at the start, end, left, right and center.
  • textBaseline – This property allows you to set the baseline of the text. The baseline is the where the text sits on. You can pass in top, bottom, middle, alphabetic, ideographic, and hanging.

All these properties are optional to set.

Conclusion

The text API is still a work in progress. You definitely will have to be careful on how you use it. It’s also not implemented in all browsers yet. For more information on drawing text in a canvas, then go here.

https://developer.mozilla.org/en-US/docs/Drawing_text_using_a_canvas

About Jasko Koyn

Check Also

Audio

Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.