The textAlign() function in p5.js is used to set the alignment for the drawing the text. This function accepts two parameter horizAlign and vertAlign. The horizAlign parameter sets the alignment on x-axis and the vertAlign parameter sets the alignment on y-axis.
Syntax:
textAlign( horizAlign, vertAlign)
or
textAlign()
Parameters: This function accepts two parameters as mentioned above and described below:
- horizAlign: This parameter stores the horizontal alignment of the text as (LEFT, CENTER, or RIGHT).
- vertAlign: This parameter stores the vertical alignment of the text as (TOP, BOTTOM, CENTER, or BASELINE).
Below programs illustrate the textAlign() function in p5.js:
Example 1: This example uses textAlign() function to align the content horizontally.
function setup() {
// Create Canvas of given size
createCanvas(380, 150);
} function draw() {
// Set the background color
background(220);
let c = 0.5;
// Use atan() function to calculate
// arc tangent value
let ac = atan(c);
// Set font size
textSize(26);
// Set font color
fill(color( 'green' ));
// Set the text alignment to
// CENTER, RIGHT, LEFT
textAlign(LEFT);
text( 'GEEKS' , 100, 30);
textAlign(CENTER);
text( 'for' , 100, 60);
textAlign(RIGHT);
text( 'GEEKS' , 100, 90);
} |
Output:
Example 2: This example uses textAlign() function to align the content vertically.
function setup() {
// Create Canvas of given size
createCanvas(380, 150);
} function draw() {
// Set the background color
background(220);
// Set the text size
textSize(26);
// Set the stroke width
strokeWeight(0.5);
// Set the co-ordinates for line
line(0, height/2, width, height/2);
// set the alignment for the text
textAlign(CENTER, TOP);
// Set the text
text( 'CENTER' , 0, height/2, width);
} |
Output:
Reference: https://p5js.org/reference/#/p5/textAlign