Beginners' question on p5js print() function

Viewed 62

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 (?).

1 Answers

This happens because draw() runs on a loop. Behind the scenes, the 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>

Related