Question

I am trying to do text masking in javascript.

Below is my code :-

if(this.image!==null)
{
   canvasContext.drawImage(this.image, 0, 0, this.width, this.height);
}

canvasContext.font = "55px Arial";
canvasContext.textAlign = "center";
canvasContext.textBaseline = "middle";   
canvasContext.globalCompositeOperation = 'destination-out';
canvasContext.fillText("CENSORED", 250, 250);

But its not working. Please help me to resolve this issues.

No correct solution

OTHER TIPS

I’m not sure what “not working” means, but…

There are 2 common kinds of text masking in canvas

destination-out: The Text will act as a cookie-cutter and remove anything drawn underneath the text, but the Text will not show on transparent pixels.

xor: The Text will cut out only non-transparent drawings on the canvas, but the Text will otherwise be drawn normally.

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/n836N/

<style>
    body{ background-color: purple; }
    canvas{background-color: white; border:1px solid red;}
</style>

<script>
$(function(){

    var canvas1=document.getElementById("canvas1");
    var canvasContext1=canvas1.getContext("2d");
    var canvas2=document.getElementById("canvas2");
    var canvasContext2=canvas2.getContext("2d");

    // destination-out 
    // Text cuts-out everything under it
    // background is revealed in the cut-out
    makeGradientAndFont(canvasContext1,canvas1);
    canvasContext1.globalCompositeOperation = 'destination-out';
    canvasContext1.fillText("CENSORED", 175, 50);

    // xor
    // Text cuts-out everything it overlaps
    // But Text is drawn normally where canvas is transparent
    // background is revealed in the cut-out
    makeGradientAndFont(canvasContext2,canvas2);
    canvasContext2.globalCompositeOperation = 'xor';
    canvasContext2.fillText("CENSORED", 175, 50);

    function makeGradientAndFont(ctx,canvas){
        var grad = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        grad.addColorStop( 0, '#0000FF');   
        grad.addColorStop(.3, '#00FFFF');
        grad.addColorStop(.4, '#99FFFF');   
        grad.addColorStop(.5, '#00FF00');
        grad.addColorStop(.6, '#FFFF00');
        grad.addColorStop(.8, '#F00000');
        ctx.rect(115, 0, canvas.width-115, canvas.height);
        ctx.fillStyle=grad;
        ctx.fill();
        ctx.fillStyle="black";
        ctx.font = "55px Arial";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle"; 
    }


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas1" width=350 height=100></canvas><br/>
    <canvas id="canvas2" width=350 height=100></canvas>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top