Reputation: 1767
I have a canvas with a solid red background. I want to draw transparent pixels on this red color, to make the pixels transparent where the text would be.
The problem I have is using the standard ctx.fillText method the pixels are painted "on top" of the red color. So if I use semi-transparent text I can see the text overlaying the red color, but that's not what I want.
I want it so that the fillText call "replaces" the pixels entirely. So a text color of "rgba(0,0,0,0)" would in effect delete the existing pixels on the canvas in the shape of the text fill.
Upvotes: 0
Views: 2010
Reputation: 12891
The canvas rendering context has a property called globalCompositeOperation which let's you select a blending mode for drawing shapes.
In your particular case the xor mode would be exact what you're looking for as it makes pixels transparent where shapes overlap - as e.g. text on a solid background.
Here's an example:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let text = "I'm transparent";
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'xor';
ctx.font = '50px Arial';
ctx.fillText(text, canvas.width / 2 - ctx.measureText(text).width / 2, canvas.height / 2);
<img src="https://picsum.photos/id/76/400/300" style="position: absolute;">
<canvas id="canvas" style="position: absolute;" width="400" height="300"></canvas>
Upvotes: 1