Day 7 - Art 1

Use software that is not intended to create art or images

Sierpinski Triangle Grid

This generative art piece visualizes the Sierpinski triangle within a grid of text characters. Originally made in Python, it dynamically calculates which positions should display a "#" based on the properties of the Sierpinski triangle, creating a fractal-like pattern. The grid adapts to the canvas size, and the pattern emerges as a result of recursive division, showcasing the self-similar nature of the triangle.

    let canvas;

    function setup() {
      // Create a canvas of size 400x400 and attach it to a DOM element with the id 'canvas-container'
      canvas = createCanvas(400, 400);
      canvas.parent('canvas-container');
      
      // Set the font size for the text
      textSize(10); // Font size determines the height of each character
      textFont('monospace'); // Use monospace font for consistent character width
      noLoop(); // Disable continuous looping (only run once)
    
      // Set the background color of the canvas to light gray
      background(200);
    
      // Calculate grid dimensions based on the canvas size
      let cellWidth = textWidth(" "); // Calculate the width of one character (space)
      let cellHeight = textSize();   // Get the height of one character
      let gridWidth = Math.ceil(width / cellWidth); // Calculate the number of columns that fit in the width
      let gridHeight = Math.ceil(height / cellHeight); // Calculate the number of rows that fit in the height
      
      // Loop through each grid position (row and column)
      for (let y = 0; y < gridHeight; y++) {
        let rows = ""; // Initialize a string to build the row of characters
        for (let x = 0; x < gridWidth; x++) {
          // Call the sierpinski function to determine if the current position should be a "#" or a space
          if (sierpinski(x, y)) {
            rows += "#"; // Add "#" if the position is part of the Sierpinski triangle
          } else {
            rows += " "; // Add space if the position is not part of the triangle
          }
        }
        // Draw the row of characters on the canvas at the appropriate y-position
        text(rows, 0, y * cellHeight + cellHeight); // Adjust the y-position by the character height
      }
    }
    
    // Function to check if a point (x, y) is part of the Sierpinski triangle
    function sierpinski(x, y) {
      // Loop to reduce x and y by dividing them by 2 (binary representation)
      while (x > 0 || y > 0) {
        // If both x and y are odd, return false (not part of the triangle)
        if (x % 2 === 1 && y % 2 === 1) {
          return false;
        }
        // Divide x and y by 2 to move to the next "level" of the triangle
        x = Math.floor(x / 2);
        y = Math.floor(y / 2);
      }
      // If the loop finishes, the point is part of the Sierpinski triangle
      return true;
    }