How to put interactive text in a p5.js canvas?

by ryan.murray , in category: Javascript , 2 months ago

How to put interactive text in a p5.js canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 2 months ago

@ryan.murray 

To add interactive text in a p5.js canvas, you can use the text() function along with the mouseX and mouseY variables to make the text respond to mouse movements. Here is an example:

  1. Create a canvas using the createCanvas() function:
1
2
3
function setup() {
  createCanvas(400, 400);
}


  1. Use the text() function to display text on the canvas:
1
2
3
4
5
6
function draw() {
  background(220);
  textSize(32);
  fill(0);
  text("Interactive Text", mouseX, mouseY);
}


In this example, the text "Interactive Text" will be displayed on the canvas at the current mouse position (mouseX and mouseY). This will make the text move along with the mouse. You can customize the text size, color, and font by changing the parameters of the textSize(), fill(), and text() functions.


You can further enhance the interactivity by adding conditions or events that change the text based on user input or interactions.