HTML 画布;给定两个 X 和两个 Y,将文本居中
我正在制作一系列矩形。这不是整个脚本,此代码实际上位于一个函数内,该函数具有 x 和 y 坐标参数以及高度和宽度参数。此函数将用于创建多个矩形。我的问题是,我需要将文本置于x、y、宽度和高度的矩形内居中......并且文本的长度将变化。
<!DOCTYPE html>
<html lang="en">
<body>
<canvas id="myCanvas" width="400" height="350">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var x = 10;
var y = 10;
var width = 180;
var height = 75;
var c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
ctx.lineWidth = 5;
ctx.strokeStyle="black";
ctx.strokeRect(x,y,width,height);
ctx.textBaseline = 'top';
ctx.font = '20px Sans-Serif';
ctx.fillStyle = 'blue';
ctx.fillText ("hello", 30, 50);
</script>
</body>
</html>
I am making a series of rectangles. This is not the entire script, this code will actually be within a function with parameters for x and y coordinates and parameters for height and width. This function will be used to create multiple rectangles. My question is that I need to center the text within rectangles of x,y,width and height ... and the text will vary in length.
<!DOCTYPE html>
<html lang="en">
<body>
<canvas id="myCanvas" width="400" height="350">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var x = 10;
var y = 10;
var width = 180;
var height = 75;
var c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
ctx.lineWidth = 5;
ctx.strokeStyle="black";
ctx.strokeRect(x,y,width,height);
ctx.textBaseline = 'top';
ctx.font = '20px Sans-Serif';
ctx.fillStyle = 'blue';
ctx.fillText ("hello", 30, 50);
</script>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在绘制文本之前使用上下文的
measureText
方法来计算文本的位置。You can use the
measureText
method of your context to calculate the position of your text before drawing it.要垂直居中,请使用以下命令:
to center vertically use this:
使用textAlign属性:
context.textAlign = 'center';
http://www.html5canvastutorials.com/tutorials/html5-canvas-text-对齐/
Use the textAlign property:
context.textAlign = 'center';
http://www.html5canvastutorials.com/tutorials/html5-canvas-text-align/