Wrong color when using loadPixels to copy image

Viewed 71

I am trying to duplicate the ellipse such that its center point of the copy is the inverse of the original position in both axes using the pixels[] array to copy pixel data to new locations. However, the copy does not have the same color (rather than black, it is pink) as the original; the colors are not copying as I intended. Why is this?


This is the code:

function setup() {
  createCanvas(600, 600);
  smooth(8);
  rectMode(CENTER);
  fill(250);
  stroke(32);
  strokeWeight(10);
}

function draw() {
    draw_();
}

function draw_() {
  background(250); 
  ellipse(100, 100, 100, 100)
  loadPixels();
  for(var i=0; i<pixels.length/2; i++)
    pixels[pixels.length-i-1] = pixels[i];
  updatePixels();
}

This is the result:

2 Answers

According to the reference, the pixels array contains information in red, green, blue, and alpha components depending on index, like this:

pixels[0] = red(myColor);
pixels[1] = green(myColor);
pixels[2] = blue(myColor);
pixels[3] = alpha(myColor);

pixels[4] = red(myColor);
pixels[5] = green(myColor);
pixels[6] = blue(myColor);
pixels[7] = alpha(myColor);

//...

So if you simply reverse the array, you aren't going to just reverse the image. You're also going to mess up the colors: you'll swap red and alpha, and green and blue.

You might be better off using the get() function, which takes an x and y argument and returns a full color. Again, more info can be found in the reference.

Thanks a lot for Kevin's help, it's worked.

  for(var i=0; i<pixels.length/2; i+=4) {
    pixels[pixels.length-i-4] = pixels[i];
    pixels[pixels.length-i-3] = pixels[i+1];
    pixels[pixels.length-i-2] = pixels[i+2];
    pixels[pixels.length-i-1] = pixels[i+3];
  }
Related