Created
February 24, 2024 12:00
-
-
Save RobinBoers/9d50ea72fe23d8d646e023571e8d495b to your computer and use it in GitHub Desktop.
p5js exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const STARTING_SIZE = getWidth(); | |
const MIN_SIZE = 5; | |
const CENTER_X = getWidth()/2; | |
const CENTER_Y = getHeight()/2; | |
let parentSideLength; | |
function start() { | |
drawFigure(STARTING_SIZE, MIN_SIZE); | |
} | |
function drawFigure(startingSize, depth) { | |
drawSquare(startingSize); | |
let i = 0; | |
while(parentSideLength > depth) { | |
drawIteration(i); | |
i++; | |
} | |
} | |
function drawIteration(index) { | |
let circleRadius = 0.5 * parentSideLength; | |
let squareSideLength = calculateSquareSideLength(circleRadius); | |
drawCircle(circleRadius); | |
drawSquare(squareSideLength); | |
} | |
function calculateSquareSideLength(circleRadius) { | |
return (2 * circleRadius) / Math.sqrt(2); | |
} | |
function drawCircle(radius) { | |
let circle = new Circle(radius); | |
circle.setPosition(CENTER_X, CENTER_Y); | |
circle.setColor(getRandomColor()); | |
add(circle); | |
} | |
function drawSquare(sideLength) { | |
let square = new Rectangle(sideLength, sideLength); | |
let { x, y } = calculateSquarePosForLength(sideLength); | |
square.setPosition(x, y); | |
square.setColor(getRandomColor()); | |
add(square); | |
parentSideLength = sideLength; | |
} | |
function calculateSquarePosForLength(sideLength) { | |
let x = CENTER_X - (0.5 * sideLength); | |
let y = CENTER_Y - (0.5 * sideLength); | |
return { x: x, y: y }; | |
} | |
function getRandomColor() { | |
return Randomizer.nextColor(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment