Question

I'm building a website and I need a user to be able to select an image (a transparent gif with black sign on it) and select a color. I have all the gifs in black with transparent background.

How can I change the color of the gif (the black only) to the color the user chose? I was thinking about using a canvas for this but I'm not sure...

Was it helpful?

Solution

You can use a canvas for this. There is no need to iterate the pixel buffer as many suggests and I would recommend avoiding if possible for two reasons:

  • CORS restriction may apply if image is loaded from a different origin
  • Performance

There is a much easier way involving composite modes:

Live demo

/// load image here, then:

function render() {

    /// this composite mode clears the canvas as well
    ctx.globalCompositeOperation = 'copy';
    ctx.drawImage(img, 0, 0);

    /// this mode fills in whatever, in the image
    ctx.globalCompositeOperation = 'source-in';

    /// color to change GIF to:
    ctx.fillStyle = '#00c';

    /// fill color into non-alpha pixels
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

The copy mode works here as the image is the only thing we want to draw to the canvas. If you need to draw in other details as well then use source-over instead and manually clear the canvas using clearRect().

Tip: You can also draw another image on top instead of a fill color.

Original GIF

Original

Changed to blue color

ctx.fillStyle = '#00c';

Blue version

Changed to red color

ctx.fillStyle = '#c00';

Red version

etc.

OTHER TIPS

Assuming that you want to change the color of the black parts of the image (not the transparent parts) you'll have to use canvas to get the black pixels of the image and draw a new image replacing these pixels with the color your user has chosen.

If you want to replace the transparent parts, simply setting a background color using CSS will do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top