chad0926
chad0926

Reputation: 11

Changing Pixel Color using Javascript For Loop

How can I change a 200x200 black image to yellow using Javascript For Loop?

What I know is that black is (0,0,0) and yellow is (255,255,0)

var img = new SimpleImage(200,200);
print(img);

for (var pixel of img.values()){
pixel.setRed(r);
pixel.setGreen(g);
pixel.setBlue(b);
}

Upvotes: 0

Views: 4616

Answers (2)

Kirthana Rajinikanth
Kirthana Rajinikanth

Reputation: 11

You`ll have to print the image after you change the pixel colors.

var img = new SimpleImage(200,200);

for (var pixel of img.values()){
    pixel.setRed(255);
    pixel.setGreen(255);
    pixel.setBlue(0); 
}
print(img);

Upvotes: 1

nylki
nylki

Reputation: 504

As @Kavian said, you would need to replace the variables (r,g,b) with the values you want. (Or alternatively define the variables beforehand). This should do the trick:

var img = new SimpleImage(200,200);
print(img);

for (var pixel of img.values()){
    pixel.setRed(255);
    pixel.setGreen(255);
    pixel.setBlue(0); 
}

What the code does, is to go through each pixel of the image iteratively and simply set every pixel to (255,255,0) which is yellow.

Also the last line in the loop pixel.setBlue(0); could be omitted if you are sure that all pixels are completely black to begin with. The above code is failsafe in that regard, as it makes sure that the pixels are yellow, regardless of the previous color value.

Upvotes: 2

Related Questions