将文本相对于html画布对齐
Aligning a text relative to the html canvas
<!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>
相关文章:
- jquery移动对齐按钮取决于内容大小
- 如何在JavaScript图像滑块内居中对齐图像
- 为什么文本对齐:对;工作不正常
- 显示可链接的搜索结果+对齐方式
- 以Jquery为中心的Div中的图像对齐
- 无法将文本与图片垂直对齐
- 在这种情况下,如何正确对齐显示
- 使用jquery垂直对齐动态加载的图像
- 如何使 DIV 中的内容垂直对齐
- '填隙'当所述项目不在容器中时,将一些项目与引导程序网格对齐
- typeahead下拉结果向右对齐-向右拉
- 按钮对链接对输入类型=“;提交”;在表格上
- 对键值对的棘手正则表达式解析
- 尝试在javascript中对键值对列表求和
- 根据属性值对键值对进行降序排序
- 在Javascript和会话存储中对键值对进行字符串化
- 对Flow中对包含可选参数的并集类型进行操作的函数进行注释
- 为什么Array.有时对某些值对进行两次排序比较
- 如何建立浏览器对浏览器(点对点)连接?
- 如何在c#中使用嵌套集合对键值对建模