知道如何在 HTML5 Canvas 中完美地居中单个字母吗?
我有这段代码可以对单词中的每个字母进行动画处理。
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)
最佳答案
只需从水平位置计算中删除 - (letterWidth/4)
即可:
ctx.fillText(letter, (canvas.width / 2), (canvas.height / 2));
关于javascript - HTML5 canvas - 字母居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33365343/