Weird behaviour with loadPixels() and updatePixels()

Hi everyone,

I got this very short sample of code where for each pixel of my canvas I draw a shade of grey:

function setup()
{
	createCanvas(200,200)
	background(0)

	loadPixels()

	for(var y = 0; y < height; y++)
		for(var x = 0; x < width; x++)
		{
			var c = (x+y)%255
			changePixelColor(x,y,c,c,c)
		}

	updatePixels()
}

function changePixelColor(x, y, r, g, b)
{
	var index = (x + y * width) * 4
	pixels[index + 0] = r
	pixels[index + 1] = g
	pixels[index + 2] = b
	pixels[index + 3] = 255
}

And this absolutely doesn’t work on my computer, here’s the result :

The expected result are those rotated gradient lines. But they should take up all the screen. Why is 3/4 of the screen still black and most importantly, why is it split in two exact same tiny rectangles ?

Am I missing something ?
Thanks for your help

1 Like

try

      var c = (x+y)%255
      set(x,y,c);
        //changePixelColor(x, y, c, c, c)

is it what you expected?

but this looks different:


function setup() {
  createCanvas(200, 200);
  background(0);
  let d = pixelDensity();

  loadPixels();
  console.log("d "+d);   //see here 2
  for (var y = 0; y < height*d; y++) {
    for (var x = 0; x < width*d; x++)
    {
      var c = (x+y)%255;
      //set(x,y,c);
      changePixelColor(x, y, c, c, c,d);
    }
  }

  updatePixels();
}

function changePixelColor(x, y, r, g, b,d)
{
  var index = (x + y * width*d) * 4;
  pixels[index + 0] = r;
  pixels[index + 1] = g;
  pixels[index + 2] = b;
  pixels[index + 3] = 255;
}

i think in respect of pix dens also need to change

c = (x+y)%255

somehow
http://p5js.org/reference/#/p5/pixels

1 Like

You solved it.
The problem was the pixel density, it was 2 by default so using set() instead of changePixelColor() or putting pixelDensity(1) at the start of the program fixes it
Thanks !

1 Like