Week 2: Loops

Concept

I was inspired by the old magazines linked in the assignment description, where multiple shapes were often drawn onto the canvas. The canvas however defaults to a line, similar to the light cycles in the original Tron movie. Because of the constant increments by default, the line will turn at consistent lengths and eventually form a grid.

To allow for multiple shapes, I put together multiple functions (e.g., drawCircle, drawTriangle, drawSquare) that the program will rotate through when the mouse is clicked. However, if the user holds down the mouse, the program will cycle through all available shapes and draw all shapes at the same time.

Code Highlight

The below snippet includes an interesting piece of my code that incorporates the randomness: The code generates a random value in the range 0 to 1, and then uses that as a mechanism to decide whether to turn left, right, or go straight. Approximately 80% of the time the code will decide straight, 10% of the time it will choose left, and 10% of the time it will choose right.

// Decide what to do based on the provided value

let randVal = Math.random();
let xDelta = 0;
let yDelta = 0;

if (randVal < 0.8) {
  direction = direction; // do nothing
} else if (randVal < 0.9) {
  direction = (direction + 90) % 360; // go clockwise
} else if (randVal <= 1.0) {
  direction = (direction - 90 + 360) % 360; // go counterclockwise
}

// Draw in direction
if (direction === 0) {
  xDelta = increment;
} else if (direction === 90) {
  yDelta = increment;
} else if (direction === 180) {
  xDelta = -increment;
} else if (direction === 270) {
  yDelta = -increment;
}

 

Demo

Hint: Clicking on the canvas will increase the frame rate and the size of the shapes. Holding <SPACE> will enable the eraser mode.

Reflection and Future Work

This was a fun project for me to put together, and I enjoyed slowly building it up with multiple steps. It is a relatively simple concept, yet incorporates additional layers of complexity as the user interacts more with the piece.

While it does incorporate a loop that draws all shapes at once when the user presses the mouse, the entire program also acts as a loop as the art board is dynamically drawn.

Future work may wish to explore additional shapes that could be added to the piece, or alternative ways for the user to interact with it. Additional threads could also be added, such that multiple lines are being drawn at the same time.

Leave a Reply