TheOne
TheOne

Reputation: 11161

Change color of an image drawn on an HTML5 canvas element

I've got this image here: enter image description here

How can I change it's entire color to a user-define rgb value?

In other words given an image in grayscale, how do I switch it back to color, with the color being any rgb value.

Upvotes: 3

Views: 3847

Answers (1)

TheOne
TheOne

Reputation: 11161

Thanks to @Rikonator's comment the solution is as follows:

function changeColor(img, r, g, b) {
    var c = document.createElement('canvas');
    c.width = img.width;
    c.height = img.height;
    var ctx = c.getContext('2d');
    ctx.drawImage(img, 0, 0);
    var imgData=ctx.getImageData(0, 0, c.width, c.height);
    for (var i=0;i<imgData.data.length;i+=4)
    {
        imgData.data[i]= r | imgData.data[i];
        imgData.data[i+1]= g | imgData.data[i+1];
        imgData.data[i+2]= b | imgData.data[i+2];
    }
    ctx.putImageData(imgData,0,0);
    return c;
},  

Upvotes: 4

Related Questions