1

I'm leveraging some of the the code from the following selected answer:

How to change color of an image using jquery

It's working very well, but when I run the code more than once, it seems like the new color is being added to the old color, so eventually everything turns black. I think my problem is not really understanding what's happening on this piece:

for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
{
    // If it's not a transparent pixel
    if(currentPixels.data[I + 3] > 0)
    {
        currentPixels.data[I]     = originalPixels.data[I] / 255 * newColor.R;
        currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
        currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
    }
}

I understand that I'm looping through all the pixels on the canvas and modifying the non-transparent ones, but what, for example is the pixel data / 255 * the new red, green or blue?

Community
  • 1
  • 1
Chords
  • 6,720
  • 2
  • 39
  • 61
  • This looks like `currentPixels === originalPixels`. Remember _JavaScript_ takes _Objects_ by reference; you'll need to create a **clone** which you store as `originalPixels`. – Paul S. Feb 25 '14 at 02:34

1 Answers1

2

You will need to separate the source image data from the destination data so that every time you run through the loop the source data is always the same as the original.

You can use two canvases for this (off-screen if you wish) where you draw the original image into one (source) and present the result in the other.

You can alternative keep a copy in memory of the imageData from the original canvas before it was modified (but with the image on it) which you reuse for each time.

What happens is that the original channel value is normalized:

value / 255

creates a value in the interval [0.0, 1.0]

Then that is multiplied with the new color which in effect acts as a per-centage of that value.

If you run this result again through the process a value will decrease each time and therefor end up as 0 (unless one of the color components are always 255).

Hope that made any sense! :)

  • Thank you so much, Ken. Just the push I needed. What I wound up doing was placing a second image element on top of the first, so I always retain the original, then continuing to swap the source of that one as needed. – Chords Feb 25 '14 at 03:20