rgbgetimagedata

use getImageData to get RGB value


I'm reading all the pixels of an image and I'm trying to get the rgb value of a pixel and change this. Currently I only get 1 variable out of this. Which varies from 1 to 255. But I can't seem to get 3 values out of this. What am I doing wrong?

<script>
var effectButton;
var paintButton;
var canvas;
var context;

function init()
{
    var image = document.getElementById('SourceImage');
    effectButton = document.getElementById('EffectButton');
    paintButton = document.getElementById('PaintButton');
    canvas = document.getElementById('Canvas');
    context = canvas.getContext('2d');

    // Set the canvas the same width and height of the image
    canvas.width = image.width;
    canvas.height = image.height;

    paintButton.addEventListener('click', function ()
    {
        drawImage(image);
    });

    effectButton.addEventListener('click', addEffect);
}

function drawImage(image)
{
  context.drawImage(image, 0, 0);
}

function addEffect()
{
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
    MakeMoreRed(imageData.data);
    context.putImageData(imageData, 0, 0);
}

function MakeMoreRed(data)
{
    for (var i = 0; i < data.length; i++ )
    {
        //How do i get the rgb value?? from data[i]
        data[i] = data[i] + 5;

        //var green = data[i] + 5;
        //var blue= data[i] + 5;
    }
}

window.addEventListener('load', init);

</script>

Solution

  • Figured it out. data basicly is a huge array. data[0] is the red value of the first pixel, data[1] is the green value of the first pixel, data[2] is the blue value of the first pixel and data[3] is the opacity value of the first pixel.

    Knowing this I made a for loop to go through every pixel.

    function MakeMoreRed(data)
    {
    var index;
    
    for(var y = 0; y < canvas.height; y++ )
    {
        for(var x = 0; x < canvas.width; x++ )
        {
            index = (x + y * canvas.width)*4;
    
            data[index+0] = data[index+0] + 5;
            data[index+1] = 0;
            data[index+2] = 0;
            data[index+3] = 255;
        }
    }
    

    }