位!
@foz正確地說,context.textAlign會自動將文本居中放置。
@ user3190532和@philipp正確地說,context.measureText將計算文本寬度以進行手動居中。
我的位逼近字體的高度,有些精確垂直居中:
var approxFontHeight=parseInt(ctx.font);
這裏的示例代碼和演示:http://jsfiddle.net/m1erickson/YjLKD/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.font="18px verdana";
// Testing
drawCenteredText("Hello",canvas.width/2,canvas.height/2);
function drawCenteredText(text,centerX,centerY){
// save the unaltered context
ctx.save();
// approximate the font height
var approxFontHeight=parseInt(ctx.font);
// alter the context to center-align the text
ctx.textAlign="center";
// draw the text centered at [centerX,centerY]
ctx.fillText(text,centerX,centerY+approxFontHeight/4);
// restore the unaltered context
ctx.restore();
// draw some guidelines just for testing
ctx.beginPath();
ctx.moveTo(centerX,0);
ctx.lineTo(centerX,canvas.height);
ctx.moveTo(0,centerY);
ctx.lineTo(canvas.width,centerY);
ctx.stroke();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=200></canvas>
</body>
</html>