TheDiamondfinderYT
TheDiamondfinderYT

Reputation: 89

p5.js Changing size using variables

I want to know how to change the size/location of an object in p5 using an infinite loop. for some reason, this doesn't work

function setup() {
  createCanvas(400, 400);
}
var size=80

function draw() {
  noFill();
    ellipseMode(CENTER);
    rectMode(CENTER);
  background(220);
  ellipse(40,40,size);
rect(40, 40, size, size);
  
}
test()
function test()
{
  size=size+1
  draw()
  setTimeout(test, 200)
}

How do i do it?

Also, here's the error message:

p5.js says: There's an error due to "noFill" not being defined in the current scope (on line 77 in about:srcdoc [about:srcdoc:77:3]).

If you have defined it in your code, you should check its scope, spelling, and letter-casing (JavaScript is case-sensitive). For more: https://p5js.org/examples/data-variable-scope.html https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_Defined#What_went_wrong Did you just try to use p5.js's noFill() function? If so, you may want to move it into your sketch's setup() function.

For more details, see: https://github.com/processing/p5.js/wiki/p5.js-overview#why-cant-i-assign-variables-using-p5-functions-and-variables-before-setup

Upvotes: 1

Views: 1030

Answers (2)

Ruskin Wadia
Ruskin Wadia

Reputation: 96

Generally functions like rectMode and ellipseMode are called in the setup function. Here is what your code should look like:

function setup() {
  createCanvas(400, 400);
  ellipseMode(CENTER);
  rectMode(CENTER);
}
var size = 80

function draw() {
  background(220);
  rect(40, 40, size, size);
  ellipse(40, 40, size);
  noFill();
}

Upvotes: 0

Steve
Steve

Reputation: 10886

The reason why you're getting the error is because the you're calling draw() before noFill, ellipse, rectMode... etc are defined, which seems to happen after your javascript. You can verify this by replacing test() with setTimeout(test), which shouldn't have that error because it should run the code after the p5 functions are defined.

In any case, as Samathingamajig says, you generally shouldn't call draw by yourself-- p5 automatically does it, defaulting to aiming to call it 60 times a second. You can just fix your code by deleting the draw() line.

Here's a working snippet:

function setup() {
  createCanvas(400, 400);
}
var size=80

function draw() {
  noFill();
  ellipseMode(CENTER);
  rectMode(CENTER);
  background(220);
  ellipse(40,40,size);
  rect(40, 40, size, size);
}
test()
function test()
{
  size=size+1
  setTimeout(test, 200)
}
<script src="https://unpkg.com/[email protected]/lib/p5.min.js"></script>

Upvotes: 1

Related Questions