javascriptp5.jsgenerative-art

How to Generate a Grid of Points Using Vectors in p5.js


I'm trying to generate a grid of points on the canvas described by vectors in order to make a flow field. I generate the vectors in a nested loop, then push them to a list, and finally attempt to draw them. However, when I attempt to draw them the .x and .y attributes aren't recognised. I think this is because the list of vectors is empty/only has one entry in it and I can't work out why. Apologies if this is a simple problem - this is my first time using javascript and p5.js. My code is shown below, it should generate a uniform grid of points.

let width = 600;
let height = 600;
let points = [];


function setup() {
  createCanvas(width, height);
  background(30);
  
  let density = 50;
  let spacing = width / density;

  for (var x = 0; x < width; x += spacing); {
    for (var y = 0; y < height; y += spacing); {
      var p = createVector(x, y)
      points.push(p)
      
    }
  }
}


function draw() {
  noStroke();
  fill(255);

  for (var i = 0; i < points.length; i++); {
    circle(points[i].x, points[i].y, 1);
  }
}

EDIT: My code is definitely generating one vector, but only one for some reason. So I believe the issue is the for loops not executing correctly.


Solution

  • Your for loop syntax is incorrect. There should not be a semicolon after the closing parenthesis and the opening curly brace:

      //                                    !
      for (var i = 0; i < points.length; i++); {
        circle(points[i].x, points[i].y, 1);
      }
    

    You will need to fix each of your for loops.