Matthew McLeod
Matthew McLeod

Reputation: 27

how do i make shorten this code that makes circles into an array?

Im using the p5.js library and cannot format a for loop properly to display these circles:

function draw() {
  ellipse(width/12,height/2,width/6,width/6);    
  ellipse(width/12,height/4,width/12,width/12);
  ellipse(width/12,height/8,width/24,width/24);
  ellipse(width/12,height/16,width/48,width/48);
}

i have tried the following but no ellipses are made. where am i going wrong?

below i have attached the full code.

for(var i = 0; i < 4; i++){
  ellipse(width/12, height/(2 * (2^i)), width/(6 * (2^i)), width/(6 * (2^i));  
}

function setup() {
  canvas = createCanvas(windowWidth,windowHeight);
}

function draw() {
  background(255);
  fill(	149, 185, 241,160);
  rect(width*(1/6),0,width*(2/3),height);
  
  
  fill(181,99,87,160);
  noStroke();
  
  for(var i = 0; i < 4; i++){
  ellipse(width/12, height/(2* pow(2,i)), width/(6 * pow(2,i)), width/(6 * pow(2,i));  
}

  
}


window.onresize = function() {
  canvas.size(windowWidth, windowHeight);
}

Upvotes: 0

Views: 64

Answers (2)

Kevin Workman
Kevin Workman

Reputation: 42176

This isn't doing what you think it is:

2^i

That's a bitwise xor operator. See this question for more info, and Google is your friend.

You're probably looking for the P5.js pow() function. More info can be found in the reference.

You should get into the habit of debugging your code. When you have questions like this, try printing out the value of each parameter. You would have been able to isolate your problem, which makes Googling easier.

For example, do this:

for(var i = 0; i < 4; i++){
  console.log('i: ' + i);
  console.log('width: ' + width);
  console.log('width/12: ' + width/12);
  console.log('pow(2,i): ' + pow(2,i));
  console.log('height/(2* pow(2,i)): ' + height/(2* pow(2,i)));
  console.log('width/(6 * pow(2,i)): ' + width/(6 * pow(2,i)));
  ellipse(width/12, height/(2* pow(2,i)), width/(6 * pow(2,i)), width/(6 * pow(2,i)));  
}

This will tell you exactly which parameter is different from what you expected, and you can further isolate your problem from there.

Of course, that also requires you to check the developer console, which you should also really get into the habit of doing. That's where any errors you're encountering will be shown. The code currently in your question is missing a ) closing parenthesis on the ellipse() line.

If you have a follow-up question, please try to post a MCVE that we can copy and paste to run ourselves instead of a disconnected snippet of code.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a left shift << operator, because you are using factor 2, like

for (var i = 0; i < 4; i++) {
    ellipse(width / 12, height / (2 << i), width / (6 * (2 << i)), width / (6 * (2 << i));
}

console.log(2 << 0, 2 << 1, 2 << 2, 2 << 3);

Upvotes: 0

Related Questions