I want to use the pixels array to randomize color in a repeated image. I think I should see three sharks with three random colors, the same random colors as the squares at the top of the canvas. But, the sharks all get the first random color. Occasionally, sharks are the second color, and very rarely, the three sharks are the three colors.
I’ve tried searching for the pixels array, but most of the code I see is using it to address a single instance of an image, not multiple instances.
I think the problem is that your test is not always performed on the same image.
The first time you loop through the pixels of the image, you do so in the original pic but you are updating the values with new colors. So then the second time, since you have changed the pixels of the image your tests ( img.pixels[i+2]>=120 && img.pixels[i]<=100) is now performed on the new image with the new values.
The reason why sometimes it works is because sometimes, you may pick a random color that does not change the result of your tests.
Hope it is clear enough. The idea to solve it is to have 2 images variables. One on wich you perform the tests without changing the values and one on which you change the values to display the result.
But, I think it would be faster and lighter to load a test version and save a manipulated version, using two variables as you suggest. The problem I’m running into is, I can’t check one copy of the image and manipulate another-- the update.pixels function won’t let me.
Broken code and error message below:
let img;
let img2;
let colorTest;
function preload() {
img = loadImage("images/blueShark.png");
img2 = loadImage("images/blueShark.png");
}
function setup() {
createCanvas(700, 600);
for (let sharks = 0; sharks < 3; sharks++){
colorTest = color(random(0,255), random(0,255), random(0,255),255);
img.loadPixels();
for (let i = 0; i < 4 * (img.width * img.height); i += 4) {
if (img.pixels[i+2]>=120 && img.pixels[i]<=100){
img2.pixels[i] = red(colorTest);
img2.pixels[i+1] = green(colorTest);
img2.pixels[i+2] = blue(colorTest);
img2.pixels[i+3] = alpha(colorTest);
}
}
print(colorTest);
img2.updatePixels();
image(img2, random(0,width-200), random(0,height-300));
}
}