Reputation: 1263
I'm just trying out p5.js. I'd like to change some HTML text (not on the p5 canvas) from p5. Something like:
score_display = createElement("text", "Score: 0");
...
score_display.nodeValue = "Score: " + score; // doesn't work
How do I do this? Thanks.
Upvotes: 4
Views: 5863
Reputation: 57155
Be careful with .html()
, it can lead to cross site scripting (XSS) attacks. It only makes sense to use html()
when you're actually setting an HTML string and are certain it's been sanitized.
Safer is to use .elt
to retrieve the native HTML element, then make an assignment to its .textContent
to change the text.
function setup() {
noCanvas();
const h2 = createElement("h2", "type into the input");
const inp = createElement("input");
inp.input(() => {
h2.elt.textContent = inp.value();
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.js"></script>
It's too bad p5 doesn't have .text()
getter/setter in its API (at the time of writing).
Upvotes: 0
Reputation: 408
let score = 0;
function setup() {
noCanvas();
scorecard = createP("Your score is " + score);
scorecard.style("background-color", "white");
}
function draw() {
score++;
scorecard.html("Your score is " +score)
}
Upvotes: 0
Reputation: 101
This is old, but I figured I'd tell you the way I would do it.
After you create the button, set its id:
score_display.id('scoreText');
Then use querySelector or getElementById to grab it like you normally would in vanilla JavaScript and set the text using textContent.
score_display_element = document.querySelector('#scoreText');
score_display_element.textContent = "Score: " + score;
Upvotes: 0
Reputation: 31
There is an .html()
property in p5.js to change innerHTML of an element.
Admittedly difficult to find in their reference documentation. Perhaps they are deprecating? https://p5js.org/reference/#/p5.Element/html
Upvotes: 3
Reputation: 1
Go tho the index.html and type in this code:
<h1>Score : <p id = "scoreText">0</p></h1>
After you put that in you html, add this code to your sketch.js:
function changeText(text){
document.getElementById("scoreText").innerHTML = text;
}
Call this function and add in the score to the parinthisis to change the text
Upvotes: 0
Reputation: 21
I think you just have to do score_display.value("")
.Then you can change score_display to whatever value you want and change the space in the parentheces to what value you want.
Upvotes: 0