stroketext()是html5 canvas中绘制空心文字的方法,仅描边不填充;需预先设置font、strokestyle和linewidth,y坐标对应文字基线,可与filltext配合实现双效效果。

在 HTML5 Canvas 中,strokeText() 是专门用于绘制空心(描边)文字的方法,它只画文字的轮廓,不填充内部。
基础用法:设置描边样式再调用 strokeText
要让 strokeText() 正常显示,必须提前设置描边颜色、线宽和字体——它**不会自动继承 fillStyle 或默认样式**。
- lineWidth:控制描边粗细(默认是 1)
- strokeStyle:设置描边颜色(支持 rgba、十六进制、关键词等)
- font:指定字体大小、字族等(必须设置,否则可能不显示或使用浏览器默认)
完整示例代码
以下是在 canvas 上绘制红色描边、2px 粗细、24px 字体的空心文字:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '24px Arial, sans-serif';
ctx.lineWidth = 2;
ctx.strokeStyle = '#ff0000'; // 描边为红色
ctx.strokeText('Hello', 50, 80); // x=50, y=80(基线位置)
关键细节提醒
- y 坐标是文字**基线(baseline)的位置**,不是顶部。若想垂直居中可配合
measureText()或用textBaseline = 'middle' - 如果只调用
strokeText()没有效果,大概率是漏设了font或strokeStyle - 可以和
fillText()同时使用,实现“描边+填充”的双效文字(先 stroke 再 fill,避免描边被覆盖) - 描边对小字号文字可能不明显,建议字号 ≥16px 并适当加大
lineWidth
进阶:让描边更清晰(抗锯齿与对齐)
Canvas 默认开启抗锯齿,但有时边缘发虚。可通过以下方式优化:
- 启用像素对齐:将坐标设为整数(如
Math.round(x)),避免半像素渲染模糊 - 关闭抗锯齿(谨慎):
ctx.imageSmoothingEnabled = false对文字影响有限,一般不推荐 - 用
shadowBlur+shadowColor模拟发光描边(非真实 stroke,属视觉技巧)
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











