jeff
jeff

Reputation: 97

Understanding non-random output when trying to create random pixels on canvas

I'm using processing.js. For each iteration of the loop within draw(), I define a random center point (x, y) anywhere on the canvas and then a random width and height between 80 and 100. This defines a rectangle. I then iterate through each point within the rectangles and determine whether a point will be drawn or not. The probability of the point being drawn is dependent on its distance from the center. I'm now trying to understand why I am so frequently seeing populated streaks from the top left to the bottom right of rectangles.

Something like this:

enter image description here

Here is my code.

void setup() {
    size(500, 500); // size of canvas
    background(0); // black background
    noLoop();
}

void draw() {

    // clusters

    int x;
    int y; // center coordinates of clusters
    int halfWidth; 
    int halfHeight; // halves of width and height of clusters

    for (int i = 0; i < 3; i++) {
        x = int(random(500));
        y = int(random(500));
        halfWidth = int(random(40, 50));
        halfHeight = int(random(40, 50));
        for (int j = x - halfWidth; j < x + halfWidth; j++) {
            for (int k = y - halfHeight; k < y + halfHeight; k++) {
                if (int(random(1, dist(x, j, y, k))) == 1) {
                    stroke(color(int(random(0, 255)), int(random(0, 255)), int(random(0, 255))));
                    point(j, k);
                }
            }
        }   
    }   
}

Upvotes: 2

Views: 40

Answers (1)

jeff
jeff

Reputation: 97

This was silly. dist() takes dist(x1, y1, x2, y2) and I had dist(x1, x2, y1, y2).

Upvotes: 2

Related Questions