简体   繁体   中英

p5.js Accessing the inidvidual pixel values

I need to access individual pixel values of the live canvas which has a pattern(shapes) drawn from user input.

like following,

function draw(){
stroke(255);
if (mouseIsPressed == true) {
   if(mouseX != old_mX || mouseY != old_mY)
      {
        obstacle[obstacle.length] = [mouseX, mouseY];
        //line(mouseX, mouseY, pmouseX, pmouseY);
        old_mX = mouseX;
        old_mY = mouseY;
      }
 }
      fill(255);
      beginShape();
      for(i = 0; i < obstacle.length;i++){
        vertex(obstacle[i][0],obstacle[i][1]);
      }
    endShape();
}

After drawing is done need to access the individual pixel values

function keyTyped() {

    if ( key == 'n')
      {
      obstacle = []
      }

    if( key == 'd'){
      loadPixels();
      //rest of the action
      updatePixels();
    }}

problem is that loadPixels(); does not loading array with correct values, loaded array is more like a random one containing random patten

is there correct way to access the pixels ?

I tried out your code, and it looks like it loads the pixels into pixels[] normally. I think the problem might be your expectation of 'normal'.

According to https://p5js.org/reference/#/p5/pixels :

The first four values (indices 0-3) in the array will be the R, G, B, A values of the pixel at (0, 0). The second four values (indices 4-7) will contain the R, G, B, A values of the pixel at (1, 0).

So, if you run loadPixels() on completely black canvas, you'll get the following array:

console.log(pixels);
-> [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255...]

0 red, 0 green, 0 blue, 255 alpha in the first pixel, then
0 red, 0 green, 0 blue, 255 alpha in the second pixel, then...

Alpha is a measure of how transparent a pixel is. 255 means it is fully opaque, 0 means it is fully transparent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM