HTML5 Game - Displays text in the center of a canvas with clip()

Introduction

Clipping function restricts the drawing area on a Canvas.

Demo

ResultView the demo in separate window

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

   //MESSAGE details. Center on Canvas.
   let mText = "Hi there!"
   let xPos  = canvas.width/2;
   let yPos  = canvas.height/2;

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

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

   //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">
You're browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

Related Topic