Monday , 20 November 2017
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

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

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

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link