Open In App

p5.js textAlign() Function

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:



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


Article Tags :