4

I'm probably missing something very obvious here. I can use p5.js in global mode and use constants for textAlign with no problem, e.g. CENTER.

Here is global mode code where it works fine:

function setup() {
  var canvas = createCanvas(720, 400);  
  canvas.parent('main_canvas');
};

function draw() { 
  textSize(32);
  textAlign(CENTER);
  text("word", 50, 50);
};

However when I try using CENTER in instance mode I get:

Uncaught ReferenceError: CENTER is not defined:

Here is instance mode code where it fails:

var s = function (p) {
  p.setup = function() {
    p.createCanvas(720, 400);
  };

  p.draw = function() {
    p.textSize(32);
    p.textAlign(CENTER);
    p.text("word", 50, 50);
  };
};
var myp5 = new p5(s,'main_canvas');

Any ideas on what I am missing here?

1
  • The point of instance mode is to keep everything related to p5.js out of the global namespace, even constants like CENTER, so this is by design. Commented Jan 13, 2022 at 0:14

1 Answer 1

4

In global mode, all the P5.js functions and variables are added to the global namespace. In instance mode, all the P5.js functions and variables are added to the variable passed into the sketch function (in your case, your p variable).

To use the CENTER variable, you have to get at it through the p variable.

In other words, you need to do this:

p.textAlign(p.CENTER);

You'll also have to do this with other variables, like mouseX and mouseY.

Sign up to request clarification or add additional context in comments.

2 Comments

The shame I feel right now knows no bounds. Thanks.
@e_r I think you've just described 75% of all programming! :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.