<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本相关</title>
<style>
body,
html {
background-color: #bfa;
overflow: hidden;
}
canvas {
margin: 150px auto;
border: 1px solid black;
display: block;
background-color: white;
}
</style>
</head>
<body>
<canvas id="test" width="300" height="300">
<span>您的浏览器版本过低,请更换IE-9以上,或使用chrome等其他浏览器</span>
</canvas>
<script type="text/javascript">
window.onload = function(){
/** @type {HTMLCanvasElement} */
//1.获取画布
var canvas = document.querySelector('#test');
if (canvas.getContext) {
//2.获取画笔
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'pink';
ctx.font = '40px sans-serif';
ctx.textAlign ="left";
/*
textAlign = value (文本对齐选项)
可选值:left,right,center
注意:!!! 左对齐 右对齐 都是相对偏移量值的位置
此处值为center时,文本的居中基于你 fillText时x的值
即:文本一半在x的左边,一半在x的右边
*/
ctx.fillText('你好啊',50,50);
}
}
</script>
</body>
</html>