我不确定“不工作”是什么意思,但是……</p>
画布中有两种常见的文本遮罩
目的地输出:文本将充当千篇一律的工具并删除文本下方绘制的任何内容,但文本不会显示在透明像素上。
xor:Text 将仅剪切画布上的不透明图形,但 Text 将正常绘制。
这是代码和小提琴: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>