Canvas How to - Clip text in the center of a canvas








Question

We would like to know how to clip text in the center of a canvas.

Answer


<!--   w  w w  .  j a v a  2 s  .  c  om-->
<!DOCTYPE HTML> <html> 
<head>
 <script>
window.onload = function()
{ 
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   var mText = "Hi there!"
   var xPos  = canvas.width/2;
   var yPos  = canvas.height/2;

   // A3. TEXT format details.
   context.font         = "60pt Comic Sans MS"; 
   context.fillStyle    = "hotpink";
   context.textAlign    = "center"; 
   context.textBaseline = "middle";

   // A4. CLIPPING region.
   context.rect(50, 60, 310, 40);
   context.clip();

   // A5. FILL text.
   context.fillText(mText, xPos, yPos);                  
}
</script> </head> <body> 
<div    style = "width:500px;   height:90px; 
                  margin:0 auto; padding:5px;">
<canvas id    = "canvasArea" 
        width = "400"  height = "150" 
        style = "border:2px solid black">
</canvas> </div> 
</body> </html>

The code above is rendered as follows: