Draw image on canvas with a filter

Viewed 72

I'm making a Zelda-like game on canvas + js and I don't how to do (or even if it can be done) to apply a filter to a sprite.

I have a scenario drawn, I have multiple characters (enemies, npcs and the player) and I'm trying to do an animation when the player kills an enemy. I'd like to make them "tilt" before I change the enemy sprite with an explosion animation. I'd like to change the whole color of the enemy sprite something like "enemy sprite -> red enemy sprite -> enemy sprite -> red enemy sprite -> explosion".

My question, can I apply a color filter to an image drawn with canvas drawImage? The code to draw the enemy into the canvas scenario is pretty simple:

ctx.drawImage(img, posX, posY, img.width, img.height);

And I have also tried this (as suggested in this other question):

ctx.globalAlpha = 0.62;
ctx.globalCompositeOperation = 'source-atop';
ctx.fillStyle = 'red';
ctx.fillRect(posX, posY, img.width, img.height);

But it applies a mask to a rectangle and not just the sprite (in this picture I applied the above code to every sprite just to watch if it worked):

Scenario and enemies

Any suggestions or help? Thanks!!

0 Answers
Related