We would like to know how to display text in the center of a canvas.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function()<!--from w w w .j a va2 s . c o m-->
{
canvas = document.getElementById("canvasArea");
context = canvas.getContext("2d");
var mText = "Hi!"
var xPos = canvas.width/2;
var yPos = canvas.height/2;
// A3. TEXT format details.
context.font = "90pt Comic Sans MS";
context.fillStyle = "lime";
context.textAlign = "center";
context.textBaseline = "middle";
// A4. FILL text.
context.fillText(mText, xPos, yPos);
}
</script>
</head>
<body>
<div style="width:200px; height:200px;
margin:0 auto; padding:5px;">
<canvas id ="canvasArea"
width ="200" height ="200"
style ="border:2px solid black">
</canvas>
</div>
</body>
</html>
The code above is rendered as follows: