0

我正在嘗試在javascript中進行文本蒙版。文本蒙版不能使用HTML畫布

下面是我的代碼: -

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); 

但它不工作。請幫我解決這個問題。

回答

0

我不知道什麼是「不工作」的意思,但是......

有2種常見的文本掩蔽在畫布

目的地出: 文本將作爲cookie-切割器並刪除文本下方繪製的任何東西,但文本不會顯示在透明像素上。

xor: 文本將在畫布上僅切出非透明圖紙,但文本將以其他方式正常繪製。

這裏是代碼和一個小提琴: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>