P5.js 像素密度问题

问题描述 投票:0回答:1

我正在 P5.js 中制作像素密度为 1 的草图。该草图的当前状态应该是生成一个 100x100 像素随机亮度的图块(如电缆静态)并在左上方。不过,我创建的平铺图像的像素密度似乎有些问题。每行随机像素之间出现大黑线。

function writeColor(image, x, y, red, green, blue, alpha) {
    let index = (x + y * width) * 4;
    image.pixels[index] = red;
    image.pixels[index + 1] = green;
    image.pixels[index + 2] = blue;
    image.pixels[index + 3] = alpha;
  }

function randomTile(size_x, size_y){
  let result = createImage(size_x, size_y);
  result.loadPixels();
  for (var y = 0; y < size_y; y++){
    for (var x= 0; x < size_x; x++){
      let brt = floor(random(256));
      writeColor(result, x, y, brt, brt, brt, 255);
    }
  }
  result.updatePixels();
  return result;
}

function setup() {
  createCanvas(600, 400);
  pixelDensity(1);
  background(0);
  let tile = randomTile(100, 100);
  image(tile, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>

输出:enter image description here

我试过弄乱像素密度并查找特定于图像的像素密度,但我并没有真正了解这里发生了什么。

javascript p5.js
1个回答
0
投票

如评论中所述,您对图块像素的索引应该相对于该图块的宽度(

size_y
)而不是p5画布
width
.

function writeColor(image, x, y, w, red, green, blue, alpha) {
  const index = (x + y * w) * 4;
  image.pixels[index] = red;
  image.pixels[index + 1] = green;
  image.pixels[index + 2] = blue;
  image.pixels[index + 3] = alpha;
}

function randomTile(sizeX, sizeY) {
  const result = createImage(sizeX, sizeY);
  result.loadPixels();

  for (let y = 0; y < sizeY; y++) {
    for (let x = 0; x < sizeX; x++) {
      const brt = floor(random(256));
      writeColor(result, x, y, sizeY, brt, brt, brt, 255);
    }
  }

  result.updatePixels();
  return result;
}

function setup() {
  createCanvas(600, 400);
  pixelDensity(1);
  background(0);
  const tile = randomTile(100, 100);
  image(tile, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

无关建议:

  • 在 JS 中使用
    camelCase
    而不是
    snake_case
  • 当您不需要重新分配变量(大多数情况下)时使用
    const
    ,而在其他任何地方使用
    let
    。避免
    var
    .
  • 当你有很长的参数列表时,考虑使用一个对象来命名参数(如果性能允许,留作练习)。
© www.soinside.com 2019 - 2024. All rights reserved.