You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

P5.js像素密度问题:生成随机亮度Tile出现黑色间隔线

解决P5.js生成Tile时出现黑色间隔线的问题

嘿,这个问题我一眼就揪出来啦!你代码里的关键错误出在writeColor函数的像素索引计算上——你误用了全局的width变量,而不是你创建的tile图像自身的宽度属性。

问题根源

在setup函数里,createCanvas(600, 400)把全局width设成了600,但你要生成的是100x100的小tile。当你在writeColor里用y * width计算行偏移时,相当于每一行都跳过了600个像素的位置,可你的tile实际只有100个像素宽,这就导致大部分像素位置根本没被正确赋值,那些未被填充的像素默认是黑色,所以才会出现一条条明显的间隔线。

修复后的代码

只需要修改writeColor函数里的索引计算,把全局width换成image.width(也就是当前操作的图像的实际宽度):

function writeColor(image, x, y, red, green, blue, alpha) {
    // 用image.width代替全局width,确保索引基于当前图像的真实尺寸计算
    let index = (x + y * image.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);
}

额外小优化

其实你还可以简化代码,把像素计算直接整合到randomTile函数里,既能减少函数调用的开销,也能降低出错概率:

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));
      let index = (x + y * result.width) * 4;
      result.pixels[index] = brt;
      result.pixels[index + 1] = brt;
      result.pixels[index + 2] = brt;
      result.pixels[index + 3] = 255;
    }
  }
  result.updatePixels();
  return result;
}

修改后,生成的100x100随机亮度tile就能正常显示,不会再有烦人的黑色间隔线啦!

内容的提问来源于stack exchange,提问作者Pixelfixation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:21:00