javascript - Text Masking not working with HTML canvas -
i trying text masking in javascript.
below 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 not working. please me resolve issues.
i’m not sure “not working” means, but…
there 2 common kinds of text masking in canvas
destination-out: text act cookie-cutter , remove drawn underneath text, text not show on transparent pixels.
xor: text cut out non-transparent drawings on canvas, text otherwise drawn normally.
here code , 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 under // background revealed in cut-out makegradientandfont(canvascontext1,canvas1); canvascontext1.globalcompositeoperation = 'destination-out'; canvascontext1.filltext("censored", 175, 50); // xor // text cuts-out overlaps // text drawn canvas transparent // background revealed in 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>