Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

685
Views
Beginners' question on p5js print() function

I have seen some closed posts on GitHub, and the occasional unsolved similar question on random returns, but I can get a good explanation as to why on a simple print() command of a defined object the object is being printed on the console seemingly in a loop:

enter image description here

I just started using p5js, and don't know javascript. So it may be where the commands are placed (function setup() or function draw()), which I am still unsure why they are defaulted on the editor start page, or else I need to specify that I want the result printed just once (?).

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This happens because draw() runs on a loop. Behind the scenes, the p5js library is using requestAnimationFrame to call draw().

You could move the print statement to be within the setup() function, which only runs once at the start of the script.

function setup() {
  createCanvas(400, 400);
  c = createVector(0,0);
  print(c.toString());
}

function draw() {
  //print(c.toString());
  background(220);
}

Or if you prefer, you can set up a conditional print block as follows:

var printed = false;
function setup() {
  createCanvas(400, 400);
  c = createVector(0,0);
  //print(c.toString());
}

function draw() {
  if (!printed) {
    print(c.toString());
    printed = true;
  }
  background(220);
}

Note: also consider using the toString method in the p5.Vector object for cleaner output.

If you need to get output from a function being called from within the draw() function, you can apply the same principles as follows:

var printed = false;

function setup(){
  createCanvas(400, 400);
  c = createVector(0,0);
  print(c);
}

function draw() {
  background(220);
}

function beingCalledWithinDraw(){
  if (!printed) {
    print(c);
    printed = true;
  }
}

Runnable example:

var printed = false;

function setup() {
  createCanvas(400, 400);
  c = createVector(0, 0);
  //print(c.toString());
}

function draw() {
  background(220);
  beingCalledWithinDraw();
}

function beingCalledWithinDraw() {
  if (!printed) {
    print(c.toString());
    printed = true;
  }
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!