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

p5.js中2D数组位图读取函数无法处理同一行重复颜色求助

问题原因与修复方案

问题根源

你代码里的block.indexOf(block2)方法只会返回当前元素在数组中第一次出现的索引。当同一行存在重复元素时,后面的重复元素会拿到和第一个元素相同的索引,导致它们的矩形都绘制在第一个元素的位置上,而原本应该绘制的位置因为没有被覆盖,显示的是背景黑色,看起来就像是重复元素变成了黑色。

修复后的代码

把遍历数组的方式改成带索引的形式,直接获取元素的准确位置,避免indexOf带来的问题:

let colors = {
  r: "red",
  g: "green",
  b: "blue",
  y: "yellow",
  o: "orange",
  bl: "black",
  w: "white",
  t: "transparent",
  i: "indigo",
  v: "violet",
  c: "cyan",
};

let myMap = [
  ["r", "o", "v", "v"],
  ["b", "i", "o", "v"],
  ["o", "y", "g", "b"],
  ["i", "v", "r", "o"],
];

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(0);
  rectMode(CENTER)
  readMap(myMap, 50, 50, 150, 150);
}

function readMap(bitmap, x = 0, y = 0, w = null, h = null) {
  // 遍历每一行,同时记录行索引rowIdx
  for (let rowIdx = 0; rowIdx < bitmap.length; rowIdx++) {
    const currentRow = bitmap[rowIdx];
    // 遍历当前行的每个元素,记录列索引colIdx
    for (let colIdx = 0; colIdx < currentRow.length; colIdx++) {
      const colorKey = currentRow[colIdx];
      fill(colors[colorKey]);
      noStroke();
      push();
      translate(x, y);
      if (w && h) scale(w/width, h/height);
      rect(
        colIdx * (width / currentRow.length),
        rowIdx * (height / bitmap.length),
        width / currentRow.length,
        height / bitmap.length
      );
      pop();
    }
  }
}

修复说明

使用普通for循环的计数器(rowIdx和colIdx)可以直接获取元素在二维数组中的准确行列位置,不受元素重复的影响。这样每个颜色对应的矩形都会被绘制到正确的坐标上,重复元素也能正常显示对应的颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:13:15