【问题标题】:Text Masking not working with HTML canvas文本屏蔽不适用于 HTML 画布
【发布时间】:2023-03-20 03:54:01
【问题描述】:

我正在尝试在 javascript 中进行文本屏蔽。

下面是我的代码:-

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

但它不起作用。请帮我解决这个问题。

【问题讨论】:

    标签: javascript html5-canvas masking globalcompositeoperation


    【解决方案1】:

    我不确定“不工作”是什么意思,但是……

    画布中有两种常见的文本遮罩

    目的地: 文本将充当 cookie-cutter 并删除文本下方绘制的任何内容,但文本不会显示在透明像素上。

    异或: 文本将仅剪切画布上的不透明图形,否则文本将正常绘制。

    这是代码和小提琴: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>
    

    【讨论】:

      猜你喜欢
      • 2014-10-14
      • 2012-06-27
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多