javascript - 获取 Canvas 中文本输入的中心

标签 javascript canvas

我正在尝试找出解决我问题的问题。

我想在 Canvas 上写一些东西,并且我想设置 x 和 y 相对于文本中间而不是开始的关系。

想象一下,您想在 Canvas 中央写“你好”。

实际上你是ctx.fillText("hello",canvas.witdh*0.5,canvas.height*0.5);

这里的问题是 H 位于中心,而不是其余部分。

我可以将文本置于双“ll”的中间吗?

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

感谢您的帮助。

最佳答案

每个答案中都有你的解决方案!

@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>

关于javascript - 获取 Canvas 中文本输入的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21878430/

相关文章:

javascript - 在 chrome 中为 console.table() 添加样式

javascript - 在这种情况下,正确的 javascript 语法应该是什么?

javascript - 需要碰撞检测的 Javascript 和 Canvas "engine"

javascript - 如何在 HTML5 Canvas 中调整图像的色调、饱和度和亮度?

javascript - 如何在 Canvas 周围绘制边框

javascript - ipython 等效于 node.js 的 javascript/coffeescript?

javascript - 展开/折叠树中的子元素(AngularJS)

javascript - 是否可以将 Canvas 设置为前景?

android - 带 Android Canvas 的圆角矩形

javascript - 没有 ID 或类的 JQuery 附加标签