Cant write to 2D-Array? Wanna set specific pixel

Hello,
I wanna try to set specific pixels, but only when the 2d-array position has an “x”. What do I wrong? I cant find the mistake I do :frowning:

//this will store the crap-mountain
var data = {};

function preload() {
  data = loadJSON('assets/mountain.json');
}

var mountainTest = Array(100).fill(0).map(() => Array(100).fill("0"));

function setup() {
  createCanvas(100,100);
  background(0);

  mountainTest[50][88].fill("x");// = "x";
  mountainTest[49][98] = "x";  
  mountainTest[50][99] = "x";
  mountainTest[49][99] = "x";
  mountainTest[51][99] = "x";
}

function draw() {
  let black = color(255, 102, 204);
  let img = createImage(100, 100);
  img.loadPixels();
  for (let i = 0; i < img.width; i++) {
    for (let j = 0; j < img.height; j++) {
      //if(mountainTest[i][j] == 'x'){
      //console.log(mountainTest[50][88]);
      img.set(i, j, color(0, 90, 102));
     //}
    }
  }
  img.updatePixels();
  //save(img, 'asstes/mountain.json');
  image(img,0,0);
}

Thanks a lot for helping!
+aeh

1 Like

did you forget to remove the comment slashes? ( // )
I tested your code, and it seems to work fine.
I did get an error on the first declaration of the mountainTest variable.
See my “changes” below
Also, don’t console.log in a for loop like this, it will slow the page down drastically, which might be why you thought it didn’t work


function setup() {
  createCanvas(100,100);
  background(0);

  mountainTest[50][88] = "x";
  mountainTest[49][98] = "x";  
  mountainTest[50][99] = "x";
  mountainTest[49][99] = "x";
  mountainTest[51][99] = "x";
}
function draw() {
  let black = color(255, 102, 204);
  let img = createImage(100, 100);
  img.loadPixels();
  for (let i = 0; i < img.width; i++) {
    for (let j = 0; j < img.height; j++) {
      if(mountainTest[i][j] == 'x'){
      img.set(i, j, color(100, 100, 102));
     }
    }
  }
  img.updatePixels();
  image(img,0,0);
}
2 Likes

Ye thanks!
It works, tbh… I havent tested it in the Browsers…I just used p5.js canvas in Visual Studio…and thought if It dont work here…it doesnt work in the web…