Reputation: 73
I'm trying to find a issue to my problem.
I want write something in the canvas, and i would like to set is x and y in relation of the middle of the text and not the start.
Imagine, you wanna write 'hello' in the center of the canvas.
actually you do ctx.fillText("hello",canvas.witdh*0.5,canvas.height*0.5);
The problem here is that the H is on center, but not the rest.
Ho can i center the text on the middle of the double 'll'?
Sometinh like ctx.fillText("hello",canvas.witdh*0.5-"hello".width,canvas.height*0.5-"hello".height);
Thank you for the help.
Upvotes: 0
Views: 2401
Reputation: 105015
Bits of your solution in each answer!
@foz correctly says that context.textAlign will automatically center your text horizontally.
@user3190532 and @philipp correctly say that context.measureText will calculate the text width to do manual centering.
My bit is to approximate the font height for somewhat-accurate vertical centering:
var approxFontHeight=parseInt(ctx.font);
Here's example code and a Demo: 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>
Upvotes: 2
Reputation: 7589
As they said, try this :
var textWidth = ctx.measureText("hello").width;
ctx.fillText("hello",canvas.witdh*0.5-textWidth*0.5,canvas.height*0.5)
and is centered on the 'll'
;)
Upvotes: 1
Reputation: 16495
I think that the canvas text metrics can help you with this. In Principle, you measure the text before you draw it. This way you can calculate the right position.
look here
Upvotes: 1
Reputation: 3369
Call this first:
ctx.textAlign = 'center';
and your existing code will do the trick I think.
Upvotes: 1