Chris Chris - 1 year ago 105
Javascript Question

How to set pixel RGB value according to image vertical strip? (JavaScript)

I have an image of 140 x 210 px that I am trying to divide into three equal vertical stripes, as follows: I need to change the red of all pixels in the left vertical third to 255, the green of all the pixels in the middle vertical to 255, and the blue of all the pixels in the right vertical third to 255. The optical effect this should have is creating a vertical red, green, and blue rainbow over the image.

I am trying to do this with the following code:

var image = new SimpleImage("hilton.jpg");
for (var p of image.values()) {
if (p.getX() < 46) {
if (46 < p.getX() < 92) {
if (p.getX() > 92) {


It adds the red and blue strips just fine to the left and right of the image, respectively. But when I try to add the green strip in the middle, it messes up the whole image, i.e., it turns green the other pixels in the image as well.

Many thanks in advance.

N.B: I am REQUIRED to modify the pixels this way (red, green, and blue to 255) by the course I am taking on Javascript right now. I know there are tons of simpler alternative solutions to the problem.

Answer Source

There's a small problem with your code:

if (46 < p.getX() < 92) {

is invalid syntax. That should be:

if (46 < p.getX() && p.getX() < 92) {

That said, without using libraries, you can only do this using an canvas, you can't just change pixels on an image:

// Setup
var canvas = document.getElementById("canvas"),
    ctx= canvas.getContext("2d"),
    img = new Image(),
    w = canvas.width / 3;

// Load image
img.crossOrigin = "anonymous";
img.src = '';

// When the image has loaded
img.onload = function(){
    // Draw it and get it's data
    ctx.drawImage(img, 0, 0);
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height),
        data =;

    // Iterate over all the pixels
    for (var i = 0; i < data.length; i += 4) {
        // The current pixels' x position
        var x = Math.floor(i / 4) % canvas.width;

        //Set the pixels' r, g, b channels if x is within certain bounds.
        if(x < w)
            data[i] = 255;   // Red
        else if(x >= w && x < w * 2)
            data[i+1] = 255; // Green
            data[i+2] = 255; // Blue

    // Re-draw the image.
    ctx.putImageData(imgData, 0, 0);
<canvas id="canvas" width="800px" height="639px"></canvas>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download