xxxxxxxxxx
65
let pixelArray; // Array to hold grayscale values
let numPoints = 20000; // Number of random points to generate
let j = 50; // Width of the pixel array
let k = 50; // Height of the pixel array
function setup() {
createCanvas(windowWidth, windowHeight);
// Initialize the grayscale pixel array with random values
pixelArray = new Array(j * k).fill(0).map(() => Math.floor(Math.random() * 256));
// Draw the grayscale pixel array
drawGrayscaleArray();
// Generate and draw random points
for (let i = 0; i < numPoints; i++) {
let x = random(-windowWidth / 2, windowWidth / 2);
let y = random(-windowHeight / 2, windowHeight / 2);
if (shouldDrawPoint(x, y)) {
fill(255, 0, 0); // Red color for the points
ellipse(x + windowWidth / 2, y + windowHeight / 2, 5, 5); // Draw the point
}
}
}
function drawGrayscaleArray() {
// Draw the pixel array as a grid of rectangles
for (let y = 0; y < k; y++) {
for (let x = 0; x < j; x++) {
let index = x + y * j;
let grayValue = pixelArray[index];
// Set fill color based on the grayscale value
fill(grayValue);
noStroke();
rect((x / j) * windowWidth, (y / k) * windowHeight, windowWidth / j, windowHeight / k);
}
}
}
function mapToPixelIndex(x, y) {
// Map the y-coordinate to the pixel array
let pixelX = Math.floor((x + windowWidth / 2) * j / windowWidth);
let pixelY = Math.floor((y + windowHeight / 2) * k / windowHeight);
// Ensure the pixel indices are within bounds
pixelX = constrain(pixelX, 0, j - 1);
pixelY = constrain(pixelY, 0, k - 1);
// Convert 2D indices to 1D index
return pixelX + pixelY * j;
}
function shouldDrawPoint(x, y) {
let index = mapToPixelIndex(x, y);
let grayscaleValue = pixelArray[index];
// Convert grayscale value to probability
let probability = 1 - (grayscaleValue / 255);
// Decide to draw the point based on probability
return random() < probability; // Return true or false based on random chance
}