将文本相对于html画布对齐

Aligning a text relative to the html canvas

本文关键字:对齐 布对齐 文本 相对于 html      更新时间:2023-09-26
<!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位置的顶部对齐文本(y位置应该是总高度的1/6)

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

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

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

您可以使用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>