Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a specific color by another in an image/sprite

I am trying to make a game with HTML5's canvas. I have some sprites, I am able to load them well, and they work fine, but some of the parts of the image are specifically #ff0000 and I would like to be able to replace it by some other color, a custom user defined color.

I don't really have a lead on this, I sort of saw image filters, but I didn't really find any examples suited for my usage, and don't have the brains to think it up on my own, trust me, I've tried.

Any help, lead, or whatsoever will be greatly appreciated.

like image 819
Alexandre Hitchcox Avatar asked Apr 26 '13 03:04

Alexandre Hitchcox


1 Answers

You can use globalCompositeOperation = "source-in"

For example, the following draws the image to a (new) canvas, and sets the colour.

    ctx.save();

    // Draw mask to buffer
    ctx.clearRect(0, 0, this.width, this.height);
    ctx.drawImage(your_image, 0, 0, this.width, this.height, 0, 0, this.width, this.height);

    // Draw the color only where the mask exists (using source-in)
    ctx.fillStyle = [your color]; // 
    ctx.globalCompositeOperation = "source-in";
    ctx.fillRect(0, 0, this.width, this.height);

    ctx.restore();

I use this exact technique to set the text colour of my bitmap fonts.

like image 94
Jarrod Avatar answered Sep 30 '22 18:09

Jarrod