2014-11-23 57 views
0

如何在畫布上設置文本對齊方式?
我的文本現在居中。
但是,當我增加或減少文本,我會得到錯誤的路線。
畫布中的錯誤對齊方式

我的代碼是:

<canvas id="puzzle" width="480" height="480"></canvas> 


var plugin = {}; 
var boardSize = document.getElementById('#canvasid').width; 
plugin.context: document.getElementById('#canvasid').getContext('2d'); 


plugin.context.fillStyle = 'rgba(255,255,255, 0.5)'; 
plugin.context.fillRect(0, 0,boardSize , boardSize); 
plugin.context.fillStyle = 'rgba(0,0,0, 1)'; 
plugin.context.font = "30px Arial"; 
plugin.context.fillText('my text goes here' , boardSize/4, boardSize/2); 

全部代碼是在這裏: https://github.com/amirhossein693/puzzle

+0

請你能提供一個http://www.sscce.org/? – InferOn 2014-11-23 12:56:36

回答

0

使用textAlign水平對齊文本的 「X」 中心點:

context.textAlign='center'; 

context.fillText('This text will be horizontally centered at x=150', 150,50); 

使用textBaseline垂直對齊文本到 「Y」 中點:

context.textBaseline='middle'; 

context.fillText('This text will be vertically centered at y=50', 150,50);