文字
核心代码
strokeText()
fillText()
* strokeText(txt, x, y, maxWidth)
* txt: 要绘制的文字
* x, y: 绘制的文字的位置
* maxWidth: 最大宽度
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>07_Canvas绘制文字</title>
<style type="text/css">
#Canvas {
border: 1px solid red;
display: block;
margin: 50px auto;
}
</style>
</head>
<body>
<canvas id="Canvas" width="1000" height="500">请升级浏览器</canvas>
<script type="text/javascript">
var Canvas = document.getElementById("Canvas");
//1. 设置宽高
Canvas.width = 1000;
Canvas.height = 500;
//2. 获取对象上下文对象(核心), 画笔
var cxt = Canvas.getContext("2d");
//3. 创建文字
var txt = "hello, world! 你好, 世界!";
//4. 设置文字属性
/*
* font属性, 设置绘制的文字的属性
* font是一个复合的属性:
* font-style: normal(正常), italic(斜体), oblique(斜体)
* font-variant:normal(正常), small-caps(单词小写字母变大写)
* font-weight:normal(正常), bold(加粗) 100-900(一般不用)
* font-size:文字大小
* font-family:字体样式
*/
cxt.font = "italic small-caps bold 20px 微软雅黑";
/*
* 5. 绘制文字
* strokeText(txt, x, y, maxWidth)
* 4个参数:
* txt: 要绘制的文字
* x, y: 绘制的文字的位置
* maxWidth: 最大宽度
*/
cxt.strokeText(txt, 100, 100, 100);
cxt.font = "normal normal normal 20px 宋体";
cxt.strokeText(txt, 100, 200, 100);
/*
* fillText
*/
cxt.fillStyle = "lightsalmon";
cxt.fillText(txt, 100, 300, 100);
</script>
</body>
</html>