2015-10-27 49 views
0

任何想法如何完美集中在HTML5画布中的单个字母?HTML5画布 - 字母居中?

我有这个代码来动画每个字母单词。

interval = setInterval(function(){ 
    ctx.fillStyle = bgColor; 
    ctx.fillRect(0,0,128,128); 
    var letter = $textInpt.val()[letterId]; 
    ctx.font = fontSize +"px "+font; 
    ctx.fillStyle = fontColor; 
    ctx.textAlign = "center"; 
    ctx.textBaseline="middle"; 
    var letterWidth = ctx.measureText(letter).width; 
    ctx.fillText(letter, (canvas.width/2) - (letterWidth/4), (canvas.height/2)); 
    letterId++; 
    if (letterId>=$textInpt.val().length) letterId = 0; 
},t); 

这是我得到(Arial字体,字体大小80px)

enter image description here

FIDDLEhttps://fiddle.jshell.net/ec265s1x/1/

回答

2

单从水平位置计算除去- (letterWidth/4)

ctx.fillText(letter, (canvas.width/2), (canvas.height/2)); 

小提琴:https://fiddle.jshell.net/ec265s1x/2/

+0

泰,我已经在我的画布容器10px的边界所以它毁了我的补偿,所以我加' - (letterWidth/4)'。现在正在工作,谢谢:) – Sko