The following code shows how to draw text with the help of these properties and methods.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML5 Canvas</title> <script type="text/javascript"> window.onload = function(){//from w ww .j a v a 2s . com let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); // draw stuff here let x = canvas.width / 2; let y = canvas.height / 2; context.font = "30px Arial"; context.textBaseline = "middle"; context.textAlign = "center"; context.lineWidth = 1; context.strokeStyle = "red"; context.fillStyle = "blue"; context.strokeText("Hello java2s.com!",x,y-50); context.fillText("Hello java2s.com!",x,y+50); }; </script> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> </body> </html>
The code above sets the font for the text using the font property.
The font size and attributes such as bold and italics must be mentioned before the font family.
The textBaseLine property controls the baseline for the text.
Some of the common values for textBaseLine property are top, bottom, and middle.
These values affect the vertical positioning of the text with respect to the y coordinate.
After setting the textBaseLine property to middle, the text is drawn with its vertical midpoint corresponding to the y coordinate.
The textAlign property controls the text alignment on the canvas.
Common values for textAlign are left, right, and center.
The textAlign property controls the alignment of the text with respect to the x position of the text.
If the x coordinate is set to 100px and textAlign is set to center, then the center of the text is placed at 100px.
We can use the strokeStyle property to specify the text outline color.
The strokeText() method draws the text on the canvas with the specified strokeStyle.
The fillStyle property controls how the text is filled.
The fillText() method draws the text with the specified fillStyle.