If condition breaks for loop in recursive function

Hi everyone! I have come across what I think may be a bug. I am just testing a recursive function which:

  1. Draws 6 circles around a circle
  2. for each circle, draw 6 circles around it.

This is the following code I wrote. (Counter was for debugging).

var r;
var counter;
function setup() {
  createCanvas(windowWidth,windowHeight);
  r = height/10;
  counter = 1;
}

function draw() {
  background(255);
  push();
  translate(width/2,height/2);
  noFill();
  rotate(millis()/1000);
  circle(0,0,r);
  circleAround(0,0,r,2);
  pop();
  
  
}

function circleAround(x,y,r,levels){
	let numSides = 6;


	
	for(i=0;i<360;i+=360/6){
		counter++;
		//console.log(counter);
		let circleX = r * cos(radians(i));
		let circleY = r * sin(radians(i));
		push()
		noFill();
		translate(circleX,circleY);
		
		

		if(levels>0){
			
			circleAround(0,0,r,levels-1);
			
		}
		circle(0,0,r);
		pop();
	}
}

This produces this output.
2019-12-29 22.45.22  3c020cbea347

I found this strange and rewrote the code in Processing. In Processing, the code produced the correct output. (I can’t post a second screenshot since I am a new user)

Is there a mistake in my Javascript? Thank you!

1 Like

screenshot

This is the output from Processing!

1 Like

Inside the function circleAround you seem to have forgotten to add var to i inside the for loop. This caused the issue.

In addition, try replacing noFill() with fill(255,0,0,40)– were you aware that several ellipses are drawn on top of each other?

2 Likes

Thanks for pointing that out! I seem to have taken the dynamic typing thing in JS for granted.

Yes, I know that they are overlapping. I finished the sketch and this is the end result:

Thanks again :grin:

3 Likes