Array 2D / 2次元配列

2次元(2D)配列を作成するための構文を示します。2D配列の値には、2つのインデックス値を通じてアクセスします。2D配列は画像の保存に便利です。この例では、各ドットは画像の中心からの距離に関連して色付けされています。

2D array nested loop
Arrays Image

View Source Code

/*
 * @name Array 2D
 * @arialabel A grid of dots drawn on a black background. Dots closer to the center are darker in color and dots further away from the center are whiter in color
 * @description Demonstrates the syntax for creating a two-dimensional (2D)
 * array. Values in a 2D array are accessed through two index values.
 * 2D arrays are useful for storing images. In this example, each dot
 * is colored in relation to its distance from the center of the image.
 */
let distances = [];
let maxDistance;
let spacer;

function setup() {
  // createCanvas(720, 360);
  createCanvas(windowWidth, windowHeight);
  maxDistance = dist(width / 2, height / 2, width, height);
  for (let x = 0; x < width; x++) {
    distances[x] = []; // create nested array
    for (let y = 0; y < height; y++) {
      let distance = dist(width / 2, height / 2, x, y);
      distances[x][y] = (distance / maxDistance) * 255;
    }
  }
  spacer = 10;
  noLoop(); // Run once and stop
}

function draw() {
  background(0);
  // This embedded loop skips over values in the arrays based on
  // the spacer variable, so there are more values in the array
  // than are drawn here. Change the value of the spacer variable
  // to change the density of the points
  for (let x = 0; x < width; x += spacer) {
    for (let y = 0; y < height; y += spacer) {
      stroke(distances[x][y]);
      point(x + spacer / 2, y + spacer / 2);
    }
  }
}

License

Source code is available on GitHub p5.js website legacy.

All examples are licensed under CC BY-NC-SA 4.0.