2014-02-19 34 views
0

我在嘗試爲我的問題找到問題。在畫布中獲取我的文本輸入的中心

我想寫在畫布上的東西,我想設置是x和y關係的文本中間,而不是開始。

想象一下,你想在畫布的中心寫'你好'。

其實你ctx.fillText("hello",canvas.witdh*0.5,canvas.height*0.5);

這裏的問題是,H是在中心,而不是休息。

何可以將文本居中放在雙'll'的中間嗎?

Sometinh像ctx.fillText("hello",canvas.witdh*0.5-"hello".width,canvas.height*0.5-"hello".height);

謝謝你的幫助。

回答

1

位!

@foz正確地說,context.textAlign會自動將文本居中放置。

@ user3190532和@philipp正確地說,context.measureText將計算文本寬度以進行手動居中。

我的位逼近字體的高度,有些精確垂直居中:

var approxFontHeight=parseInt(ctx.font); 

這裏的示例代碼和演示:http://jsfiddle.net/m1erickson/YjLKD/

enter image description here

<!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> 
0

調用此第一:

ctx.textAlign = 'center'; 

和您現有的代碼就可以了,我認爲。

1

我認爲畫布文本指標可以幫助你做到這一點。原則上,您在繪製文本之前先測量文本。這樣你可以計算出正確的位置。

here

0

正如他們所說,試試這個:

var textWidth = ctx.measureText("hello").width; 
ctx.fillText("hello",canvas.witdh*0.5-textWidth*0.5,canvas.height*0.5) 

,並集中在 'LL'

;)在每個回答您的解決方案

相關問題