Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring PNG file area if its not transparent

Do You know any good solution (also can be based on canvas), that gives developer ability to change color (fill with hex color) of png image in non-trasparent area (like a mask)? I need transparent area that will change color (or background image), thats why It has to be untouched.

like image 999
poslinski.net Avatar asked Oct 27 '25 06:10

poslinski.net


1 Answers

To do what you want you need to use getImageData and putImageData check out mdn for an explanation on pixel manipulation.

Heres some sample code

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    image = document.getElementById("testImage");

canvas.height = canvas.width = 135;
ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, 135, 135),
    pix = imgd.data,
    newColor = {r:0,g:100,b:200};

for (var i = 0, n = pix.length; i <n; i += 4) {
    var r = pix[i],
            g = pix[i+1],
            b = pix[i+2];

        if(r == 216 && g == 6 && b == 6){ 
            // Change the red to whatever.
            pix[i] = newColor.r;
            pix[i+1] = newColor.g;
            pix[i+2] = newColor.b;
        }
}

ctx.putImageData(imgd, 0, 0);​

Example demo

With the above code you could check for fuschia by using

if(r == 255 && g == 0 && b == 255)

Then just change newColor to the replacement color.

like image 99
Loktar Avatar answered Oct 28 '25 20:10

Loktar