文本属性
- 字体:fontcanvas里得font属性和css的font属性是一样的,它可以设置文本的粗细、字号、字体等
- css设置字体:
p{font:bold 18px serif} - canvas设置字体:
ctx.font = 'bold 18px serif'
- css设置字体:
- 水平对齐: textAlign下方文字的x位置都是一样,都是垂直虚线的x位置,它们的textAlign的属性各不相同

- start和end受html的dir属性影响


默认情况:<html dir="ltr"> <html dir="rtl">
- 垂直对齐: textBaselinen

| alphabetic | 默认。标准字母基线对齐 |
|---|---|
| top | 上对齐 |
| hanging | 悬挂基线对齐 |
| middle | 垂直居中 |
| ideographic | 表意基线对齐 |
| bottom | 下对齐 |
文本的绘制方法
- 填充文字
fillText(text, x, y, maxWidth) - 描边文字
strokeText(text, x, y, maxWidth) - 获取文字宽度的方法:
measureText(text)
布艺文字
- 要点:fillText(), strokeText(), setLineDash(), shadowColor, shadowBlur, shadowOffsetY

实现上图的代码如下:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>文本</title><style>body {margin: 0;overflow: hidden}</style></head><body><canvas id="canvas"></canvas><script>const canvas = document.getElementById('canvas');canvas.width = window.innerWidth;canvas.height = window.innerHeight;const ctx = canvas.getContext('2d');/*文字内容*/const text = 'canvas';/*文字位置*/const [x, y] = [50, 200];/*字体属性,文字加粗,大小:200px,字体:arial*/ctx.font = 'bold 200px arail';/*投影,颜色:rgba(0,0,0,0.6),垂直偏移:2,模糊:4*/ctx.shadowColor = 'rgba(0,0,0,0.6)';ctx.shadowOffsetY = 2;ctx.shadowBlur = 4;/*填充文字,颜色:#a76921*/ctx.fillStyle = '#a76921';ctx.fillText(text, x, y);/*实线描边文字,颜色:#f0d5ac,线宽:8*/ctx.strokeStyle = '#f0d5ac';ctx.lineWidth = 8;ctx.strokeText(text, x, y);/*虚线描边文字,颜色:#333,线宽:1,线段长度[5,3]*/ctx.strokeStyle = '#333';ctx.lineWidth = 1;ctx.setLineDash([5, 3]);ctx.strokeText(text, x, y);</script></body></html>
