1

I'm trying to put interactive text inside of a p5.js canvas but can't figure out how. By interactive text, I mean text you can highlight and copy, like text on any HTML website. Is there a way to do that? If not, what's the best framework for coding applications that use interactive text as well as elements that are in p5.js?

Speedrace
  • 25
  • 6

2 Answers2

2

P5's canvas is just that, a canvas. (More specifically a <canvas> element's rendering context). Think of it as one big, easy to edit, picture. And there's the problem, you cant highlight/copy text in a picture right. Same with canvas and text(). It just draws the text you supplied as an image to the canvas, so no actual text exists, just a bunch of image data, that when displayed, looks like like text. You might be better off using createP() or createDiv() for this one, which creates actual text that the browser can highlight/copy. Simply replace text('bla bla bla') with createP('bla bla bla'), then use css to position it, change the font, change the color. etc.

Bagel03
  • 725
  • 7
  • 22
  • 2
    My problem with that is that the text won't be on top of the canvas. Are you saying it's completely impossible to put text on top of a canvas element? – Speedrace Oct 04 '20 at 22:37
  • @Bagel03 the createP, createDiv, etc. creates & returns a pointer to a [p5.Element](https://p5js.org/reference/#/p5.Element), so you don't have to use CSS to "position it, change the font, change the color. etc." – Samathingamajig Oct 05 '20 at 02:19
  • Yea your right, I see that you posted an answer which OP should look at too. – Bagel03 Oct 05 '20 at 23:09
2

See this code that I wrote for this other question (not a duplicate) (the code isn't doing exactly what I say below but it will give the general gist)

The simple answer: p5's text() is just drawing text to the canvas. You need to use the createP() function (or createDiv)

Example code:

let myPTag;

function setup() {
  createCanvas(400, 400);
  background(200);

  myPTag = createP("This here is some text");
  myPTag.position(200, 100);
}

Click here to see this code in action

You don't need to use your own CSS for this, just use the <element>.position(posX, posY); function. To change the value of the text, just use <element>.html(newTextString);

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34