Is there any way to get and set pixel color values in a createGraphics() object?

Viewed 686

So I'm aware how you can use loadPixels() and updatePixels() to alter the individual pixels of the main canvas as though it were a bitmap. Is there any similar technique for accessing the pixels of a createGraphics() object? Or do I have to write it to the canvas then manipulate that?

Or am I supposed to use a drawingContext object somehow?

1 Answers

If you want to manipulate pixels use createImage()

If you want to draw easily using the graphics functions use createGraphics() and loadPixels() / reading pixels[] should work:

var buffer;

function setup() {
  createCanvas(400, 400);
  
  buffer = createGraphics(10,10);
  buffer.ellipse(5,5,5);
  buffer.loadPixels();
  console.log(buffer.pixels);
}

function draw() {
  background(220);
  image(buffer,0,0,400,400);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

You can of course write pixels into PGraphics too if you want. PImage is a bit lighter weight if you don't need the drawing functionality and just need pixels.

Here's an example:

var buffer;
  
function draw() {
  background(220);
  image(buffer,0,0,400,400);
}

function setup() {
  createCanvas(400, 400);
  buffer = createGraphics(10,10);
  buffer.ellipse(5,5,5);
  buffer.loadPixels();
  // print pixels (list of bytes in order (e.g. [r0,g0,b0,a0,r1,g1,b1,a1,...])
  console.log(buffer.pixels);
  
  var gradientW = 3;
  var gradientH = 3;
  for(var y = 0; y < gradientH; y++){
    for(var x = 0; x < gradientH; x++){
      // calculate 1D index from x,y
      let pixelIndex = x + (y * buffer.width);
      // note that as opposed to Processing Java, p5.Image is RGBA (has 4 colour channels, hence the 4 bellow)
      // and the pixels[] array is equal to width * height * 4 (colour cannels)
      // therefore the index is also * 4
      let rIndex = pixelIndex * 4;
      
      console.log('x',x,'y',y,'pixelIndex',pixelIndex,'red index',rIndex);
      // access and assign red
      buffer.pixels[rIndex]     = round(map(x,0,3,0,255));
      // access and assign green
      buffer.pixels[rIndex + 1] = round(map(y,0,3,0,255));
      // access and assign blue
      buffer.pixels[rIndex + 2] = 255 - buffer.pixels[rIndex] + buffer.pixels[rIndex + 1] 
      // access and assign alpha
      buffer.pixels[rIndex + 3] = 255;
      
    }
  }
  
  buffer.updatePixels();
}

function draw() {
  background(220);
  image(buffer,0,0,width,height);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Related