How to get bounding shape for wrapped text in p5.js?

Member

by domenico , in category: Javascript , 11 days ago

How to get bounding shape for wrapped text in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 10 days ago

@domenico 

To get the bounding shape for wrapped text in p5.js, you can use the textBounds() function. This function returns a rectangle that bounds the rendered text. Here's an example code snippet to demonstrate how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
let textToWrap = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet semper dolor.";
let x = 50;
let y = 50;
let maxWidth = 200;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  // Set the font
  textSize(16);
  
  // Wrap the text within the specified maximum width
  let bounds = font.textBounds(textToWrap, x, y, maxWidth);
  
  // Draw the wrapped text
  fill(0);
  text(textToWrap, x, y, bounds.w, bounds.h);
  
  // Draw rectangle around the bounding shape
  noFill();
  stroke(255, 0, 0);
  rect(bounds.x, bounds.y, bounds.w, bounds.h);
}


In this code snippet, we first define the text to wrap, the text position (x and y), and the maximum width for wrapping. In the draw() function, we use the textBounds() function to get the bounding shape of the wrapped text. We then draw the wrapped text using the text() function and draw a red rectangle around the bounding shape using the rect() function. This will give you the bounding shape for the wrapped text in p5.js.