<!DOCTYPE html>
<html>
<head>
<title>文本对齐方式</title>
<meta charset="utf-8">
</head>
<body>
<canvas id="myCanvas" width="350" height="250" style="border:solid">
你的浏览器不支持canvas画布元素,请更新浏览器获得演示效果。
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.lineWidth = 2;
context.beginPath();
context.moveTo(170, 10);
context.lineTo(170, 230);
context.stroke();
context.font = "30px Arial";
context.textAlign = "start";
context.fillText("Hello World!", 170, 50);
context.textAlign = "end";
context.fillText("Hello World!", 170, 90);
context.textAlign = "left";
context.fillText("Hello World!", 170, 130);
context.textAlign = "right";
context.fillText("Hello World!", 170, 170);
context.textAlign = "center";
context.fillText("Hello World!", 170, 210);
</script>
</body>
</html>
运行效果:
样例代码:
<!DOCTYPE html>
<html>
<head>
<title>文本对齐基线</title>
<meta charset="utf-8">
</head>
<body>
<canvas id="myCanvas" width="400" height="250" style="border:solid">
你的浏览器不支持canvas画布元素,请更新浏览器获得演示效果。
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.lineWidth = 2;
context.beginPath();
context.moveTo(10, 50);
context.lineTo(390, 50);
context.moveTo(10, 120);
context.lineTo(390, 120);
context.moveTo(10, 190);
context.lineTo(390, 190);
context.stroke();
context.font = "30px Arial";
context.textBaseline = "bottom";
context.fillText("Hello World!", 20, 50);
context.textBaseline = "top";
context.fillText("Hello World!", 220, 50);
context.textBaseline = "ideographic";
context.fillText("Hello World!", 20, 120);
context.textBaseline = "hanging";
context.fillText("Hello World!", 220, 120);
context.textBaseline = "alphabetic";
context.fillText("Hello World!", 20, 190);
context.textBaseline = "middle";
context.fillText("Hello World!", 220, 190);
</script>
</body>
</html>
运行效果:
至此,javascript中的canvas元素的基础功能就基本说完了。