【问题标题】:Aligning a text relative to the html canvas相对于 html 画布对齐文本
【发布时间】:2014-08-06 01:41:32
【问题描述】:
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="800" height="450" style="border:1px solid #d3d3d3; background-color:#999999;">

Your browser does not support the HTML5 canvas tag.</canvas>

<script>

<!--normal canvas code-->

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

<!--code for the text line-->

ctx.font = "42px Arial";

<!--place the words in mid x position and in upper 1/6 of y position-->

var canvasxposition = (c.width/2)-(ctx.fillText.x/2)

var canvasyposition = c.height/6

ctx.fillText("Hello World",canvasxposition,canvasyposition);

</script>

</body>
</html>

我正在使用画布,稍后将用于图像。 我需要在 x 位置的中间和顶部 y 位置对齐文本(总高度的 1/6 应该是 y 位置)

我用上面的代码,发现下面这行有问题。

我需要知道它有什么问题。我想在画布的中间(y 轴)看到文本的中间(y 轴)。

var canvasxposition = (c.width/2)-(ctx.fillText.x/2)

【问题讨论】:

    标签: javascript html css html5-canvas alignment


    【解决方案1】:

    您可以使用 context.textAlign 将文本从其自身的水平中心点对齐

    您可以使用 context.textBaseline 将文本从其自身的垂直中心点对齐:

    // align text from horizontal and vertical centerpoint of text
    ctx.textAlign="center";
    ctx.textBaseline="middle";
    

    示例代码和演示:http://jsfiddle.net/m1erickson/nT37D/

    <!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(){
    
        // get references to canvas and context
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
    
        // crosshairs
        ctx.beginPath();
        ctx.moveTo(0,canvas.height/6);
        ctx.lineTo(canvas.width,canvas.height/6);
        ctx.moveTo(canvas.width/2,0);
        ctx.lineTo(canvas.width/2,canvas.height);
        ctx.stroke();
    
        // align text from horizontal and vertical centerpoint of text
        ctx.textAlign="center";
        ctx.textBaseline="middle";
    
        // sample text
        ctx.font="18px arial";
        ctx.fillText("Hello World",canvas.width/2,canvas.height/6);
    
    }); // end $(function(){});
    </script>
    </head>
    <body>
        <h4>Align text from horizontal and vertical centerpoint of text</h4>
        <canvas id="canvas" width=300 height=300></canvas>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 2018-11-30
      • 2014-08-10
      • 1970-01-01
      相关资源
      最近更新 更多