Sir
Sir

Reputation: 8280

Colourize an image in canvas?

I was wondering if there is a way to draw an image but give it a colourized effect.

If you consider games, when you want to place a sprite but theres an object in the way, often the object you try to place get a red tint to it to indicate it cannot be placed which is what im trying to achieve.

I currently draw it with an opacity here:

ctx.globalAlpha = 0.5                   
ctx.drawImage(image,abposx,abposy);

Is this possible to achieve without a library?

Upvotes: 1

Views: 150

Answers (1)

Ry-
Ry-

Reputation: 224913

You can draw a semitransparent rectangle over top of it. For example:

ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // 1/2 opacity red
ctx.fillRect(0, 0, 30, 30); // Draw this over top of your image

Here's a demo.

For isometric images, all you have to do is create the appropriate path. Here's an example of that:

You can clip the overlay to your image by setting the globalCompositeOperation to source-atop:

ctx.globalCompositeOperation = 'source-atop';
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // 1/2 opacity red
ctx.fillRect(0, 0, 30, 30); // Draw this over top of your image
ctx.globalCompositeOperation = 'source-over';

Here's a demo. You may also have to use a shadow canvas if the areas you're trying to draw on also have content, though.

Upvotes: 3

Related Questions